LoginSignup
7
5

More than 5 years have passed since last update.

カスタムビュー(CustomView)の高さを可変にする設定(主にconstraints)

Last updated at Posted at 2016-11-03

UIViewをカスタムビューで作りたいときのやり方を考える

用意するファイル

  • storyboard(仮名: Main.storyboard)
  • viewController.swift(仮名: MainViewController.swift)
  • view.swift(仮名: CustomView.swift)
  • view.xib(仮名: CustomView.xib)

各ファイルの中身

MainViewController.swift
class MainViewController: UIViewController {

    @IBOutlet weak var customView: customView!

    override func viewDidLoad() {
        super.viewDidLoad()
        customView.set()
        print("ViewControllerのviewDidLoad")
        print(customView.frame)
    }

    override func viewWillAppear(animated: Bool) {
        print("ViewControllerのviewWillAppear")
        print(customView.frame)

    }
}
CustomView.swift
class ChildInfoView: UIView {
    @IBOutlet weak var xxxLabel: UILabel!    

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.xibSetup()
    }

    func set(){
        xxxLabel.text = "hoge"
    }

    private func xibSetup() {
        let view = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil).first as! UIView
        view.frame = self.bounds
        view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]

        print("CustomView.swiftのinit内")
        print(frame)

        self.addSubview(view)
    }

下準備

  1. storyboardにviewControllerを一つ置いて、クラス名をviewControllerに指定する
  2. viewController内にviewを置いて、クラス名をCustomViewに指定する

正解のconstraints設定

  1. UIViewのheight>=10、priority=1000
  2. UIViewのheight=10, priority=750

※ 10はstoryboard上の見た目になる。1以上ならなんでもいい
constraints.png

各箇所でのframeの値

CustomView.swiftのinit内
(0.0, 20.0, 375.0, 10.0)

ViewControllerのviewDidLoad
(0.0, 0.0, 40.0, 10.0)

ViewControllerのviewWillAppear
(0.0, 0.0, 375.0, 90.0)

失敗のconstraints設定

  1. UIViewのheight=80、priority=1000 Screenshot at 11月 03 23-39-54.png

各箇所でのframeの値

CustomView.swiftのinit内
(0.0, 20.0, 375.0, 80.0)

ViewControllerのviewDidLoad
(0.0, 0.0, 40.0, 80.0)

ViewControllerのviewWillAppear
(0.0, 0.0, 375.0, 80.0)

結論

heightのpriority=1000は>=xxにする
heightの=xxxはpriority=750にする
ことでカスタムビューの高さを可変にできました。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5