Ios 向文本视图添加约束在Swift中不起作用
我正在使用XCode 6.1,我正在尝试向TextView添加约束。通过将以下代码行添加到我的ViewController的viewDidLoad()函数中,我已经成功地完成了此任务:Ios 向文本视图添加约束在Swift中不起作用,ios,swift,constraints,xcode6.1,Ios,Swift,Constraints,Xcode6.1,我正在使用XCode 6.1,我正在尝试向TextView添加约束。通过将以下代码行添加到我的ViewController的viewDidLoad()函数中,我已经成功地完成了此任务: myButton.backgroundColor = UIColor.orangeColor() myButton.setTitle("New test old button", forState: .Normal) self.view.addSubview(myButton) m
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))
欢迎来到堆栈溢出,@Alex。如果您发现我的答案解决了您的问题,请单击我答案旁边的空心复选标记将其变为绿色,以接受我的答案。谢谢