0
我試圖用Swift 3以編程方式構建窗體,並且出於某種原因在運行應用程序時沒有應用正確的約束。iOS Swift 3/XCode 8右約束沒有應用
我有什麼是UIScollView
含有UITextField
,你可以從下面的滾動型預覽看到的是紅色和文本字段是白色的。
// 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
代替,但沒有什麼工作。任何建議將不勝感激。