UI部品をコード記述で、iphone7など(4.4inch)のサイズでレイアウトしているのですが、NSLayoutAnchorを使ってスクロールビューに制約を付けた場合、その上にaddSubviewしているUI部品なども連動して、4.4inchのレイアウトのまま5.5inchに合うように拡大して欲しいのですが、スクロールビューのみ変化します。
コード記述で不足や間違い(制約の付け方)などがあるのか、それぞれのUI部品に個別に制約を付けるコードを記述しなければいけないのか?・・・など、教えて頂けないでしょうか。
他の方法で画面サイズの違いに互換性を持たせることができるのでしたらその方法でもかまいません。
宜しくお願い致します。
■ iPhone7(4.7inch)でビルド
(レイアウトの理想図)
■ iPhone7Plus(5.5inch)でビルド
(NSLayoutAnchor記述なし) (スクロールビューにNSLayoutAnchor記述)
余白ができる スクロールビューのみ変化あり
import UIKit class ViewController: UIViewController,UIScrollViewDelegate { let scrollView = UIScrollView() var scrollViewContentHeight:CGFloat = 667 var labelsMaxY: CGFloat = 100 let titleLabel = UILabel() let aLabel = UILabel() let bLabel = UILabel() let cLabel = UILabel() var labels = [UILabel]() override func viewDidLoad() { super.viewDidLoad() scrollView.frame.size = CGSize(width: 375, height: 667) scrollView.contentSize = CGSize(width: 375, height: scrollViewContentHeight) scrollView.bounces = false scrollView.indicatorStyle = .default scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5) scrollView.delegate = self scrollView.backgroundColor = UIColor.yellow scrollView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(scrollView) // NSLayoutAnchor scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true scrollView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true // タイトルラベル titleLabel.frame = CGRect(x: 20, y: 20, width: 335, height: 20) titleLabel.text = "タイトルラベル" titleLabel.backgroundColor = UIColor.magenta scrollView.addSubview(titleLabel) // ABCラベル aLabel.frame = CGRect(x: 20, y: 50, width: 100, height: 30) aLabel.text = "Aラベル" aLabel.backgroundColor = UIColor.red scrollView.addSubview(aLabel) bLabel.frame = CGRect(x: 137.5, y: 50, width: 100, height: 30) bLabel.text = "Bラベル" bLabel.backgroundColor = UIColor.green scrollView.addSubview(bLabel) cLabel.frame = CGRect(x: 255, y: 50, width: 100, height: 30) cLabel.text = "Cラベル" cLabel.backgroundColor = UIColor.cyan scrollView.addSubview(cLabel) // ラベル量産 for index in 0..<20 { let label = UILabel() label.frame = CGRect(x:20, y:100+(40*index), width:335, height:40) label.text = "test(index + 1)" if index % 2 == 0 {label.backgroundColor = UIColor.gray} if index % 2 == 1 {label.backgroundColor = UIColor.lightGray} labels.append(label) scrollView.addSubview(label) } // 表示されてるラベルのmaxYを取得 var sum: CGFloat = 100 for index in 0..<labels.count { if labels[index].isHidden == false { let height = labels[index].frame.height sum += height labelsMaxY = sum } } // scrollViewContentHeightの値を再設定 scrollViewContentHeight = labelsMaxY + 100 scrollView.contentSize.height = scrollViewContentHeight } //viewDidLoadを閉じる }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/11 07:20