ios - 向 TextView 添加约束在 Swift 中不起作用

标签 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)
    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,但我需要这些约束才能正确格式化所有内容。

有人知道我做错了什么吗?

最佳答案

您需要为 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))

关于ios - 向 TextView 添加约束在 Swift 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27155917/

相关文章:

ios - 如何将底部颜色从黑色渐变替换为白色渐变?

ios - 带有 xib 文件和自定义构造函数的自定义 UITableViewCell

ios - 如何让按钮根据按下的行显示不同的视频?

ios - 基于Segment-Control将数组加载到TableView

ios - 多屏支持 iOS 8+

javascript - 来自共享或操作扩展 ios 的网络请求

ios - 使用 Core Data 和 validateForUpdate - 如何将焦点设置到文本框。

ios - 在 TableView 委托(delegate)方法中发出异步请求

ios - 如何在 iOS 中为特定设备设置顶部空间限制?

sql-server-2005 - 仅具有一个值的检查约束 SQL Server 2005