2017-02-14 13 views
0

Swift 3を使用してプログラムでフォームを作成しようとしていますが、アプリを実行するときに正しい制約が適用されません。iOS Swift 3/XCode 8右の制約が適用されていません

私が持っているものはUIScollViewです。UITextFieldが含まれています。下のプレビューから見ると、ScrollViewは赤で、TextFieldは白です。

// View Controller Properties 
var scrollView: UIScrollView! 
var firstName: UITextField! 

// Inside viewDidLoad() 
self.scrollView = UIScrollView() 
self.scrollView.translatesAutoresizingMaskIntoConstraints = false 
self.scrollView.backgroundColor = UIColor.red 
self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) 

self.view.addSubview(self.scrollView) 

let top  = NSLayoutConstraint(item: self.scrollView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0) 
let left = NSLayoutConstraint(item: self.scrollView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 0) 
let right = NSLayoutConstraint(item: self.scrollView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0) 
let bottom = NSLayoutConstraint(item: self.scrollView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0) 

self.view.addConstraints([top, left, right, bottom]) 



self.firstName = UITextField() 
self.firstName.translatesAutoresizingMaskIntoConstraints = false 
self.firstName.backgroundColor = UIColor.white 
self.firstName.placeholder = "First Name" 

self.scrollView.addSubview(self.firstName) 

let top  = NSLayoutConstraint(item: self.firstName, attribute: .top, relatedBy: .equal, toItem: self.scrollView, attribute: .top, multiplier: 1, constant: 20) 
let left = NSLayoutConstraint(item: self.firstName, attribute: .left, relatedBy: .equal, toItem: self.scrollView, attribute: .left, multiplier: 1, constant: 20) 
let right = NSLayoutConstraint(item: self.firstName, attribute: .right, relatedBy: .equal, toItem: self.scrollView, attribute: .right, multiplier: 1, constant: 0) 
let height = NSLayoutConstraint(item: self.firstName, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40) 

self.scrollView.addConstraints([top, right, left, height]) 

私の代わりに.trailing.trailingMarginを使用しますが、何も作業していない試してみました。どんな提案も大歓迎です。

let margins = view.layoutMarginsGuide 
view.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 20).isActive = true 

注:iOSの9の場合+

あなたはこのコードを使用することができます

Preview

答えて

0

関連する問題