Swift 親Viewと同じサイズに追従するViewをコードで追加する

コード全体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import UIKit
import PDFKit
 
class ViewController: UIViewController {
    var pdfView: PDFView!
 
    override func viewDidLoad() {
        super.viewDidLoad()
 
        self.pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
        self.pdfView.backgroundColor = .blue
        self.view.addSubview(self.pdfView)
        self.pdfView.translatesAutoresizingMaskIntoConstraints = false
        self.pdfView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.pdfView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.pdfView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        self.pdfView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    }
}

Viewの生成と親Viewへ追加

1
2
self.pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
self.view.addSubview(self.pdfView)

AutoLayoutの設定

Storyboardの場合

コードの場合:NSLayoutAnchorを使用する

1
2
3
4
5
self.pdfView.translatesAutoresizingMaskIntoConstraints = false
self.pdfView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.pdfView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.pdfView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.pdfView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

translatesAutoresizingMaskIntoConstraints
Documentより

ビューの自動サイズ変更マスクを自動レイアウト制約に変換するかどうかを決定するブール値です。

AutoLayout使用時はfalseに設定

注意
制約設定はaddSuview前にやるとエラーになります。

Terminating app due to uncaught exception 'NSGenericException’, reason: 'Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That’s illegal.’

Swift

Posted by shi-n