[英]Adding constraints to a TextView does not work in Swift
我正在使用XCode 6.1,正在尝试向TextView添加约束。 通过将以下代码行添加到ViewController的viewDidLoad()函数中,我已经成功完成了它:
myButton.backgroundColor = UIColor.orangeColor()
myButton.setTitle("New test old button", forState: .Normal)
self.view.addSubview(myButton)
myButton.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addConstraint(NSLayoutConstraint(item: myButton, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 20.0))
self.view.addConstraint(NSLayoutConstraint(item: myButton, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 200.0))
但是,当我尝试对TextView执行相同操作时,我无法在iOS模拟器的屏幕上看到它:
var textView = UITextView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))
textView.text = "My test text!"
textView.sizeToFit()
textView.backgroundColor = UIColor.purpleColor()
self.view.addSubview(textView)
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: 10.0))
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 400.0))
如果要删除三个约束特定行,则将创建TextView,但是我需要这些约束才能正确格式化所有内容。
有人知道我在做什么错吗?
您需要为文本视图的宽度和高度添加约束:
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 300.0))
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 300.0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.