UITextView不适合内容

时间:2016-06-10 18:28:07

标签: ios layout uiview uitextview

我正在使用此代码创建一个UITextView,假设它适合UIView容器:

// Make the cellTextView.
let cellTextView = UITextView()
cellTextView.backgroundColor = UIColor.clearColor()
cellTextView.translatesAutoresizingMaskIntoConstraints = false
cellTextView.scrollEnabled = false
superview.addSubview(cellTextView)

// Constrain the cellTextView.
cellTextView.topAnchor.constraintEqualToAnchor(superview.topAnchor, constant: 8).active = true
cellTextView.bottomAnchor.constraintEqualToAnchor(superview.bottomAnchor, constant: -8).active = true
cellTextView.leadingAnchor.constraintEqualToAnchor(superview.leadingAnchor, constant: 8).active = true
cellTextView.trailingAnchor.constraintEqualToAnchor(superview.trailingAnchor, constant: -8).active = true

但它产生了这个结果: Look at the padding

这应该是这样的: No padding

我尝试了很多不同的东西,但没有任何修复它。 任何建议将不胜感激。

2 个答案:

答案 0 :(得分:0)

摆脱你用作边距的常数。这将解决它。

// Make the cellTextView.
let cellTextView = UITextView()
cellTextView.backgroundColor = UIColor.clearColor()
cellTextView.translatesAutoresizingMaskIntoConstraints = false
cellTextView.scrollEnabled = false
superview.addSubview(cellTextView)

// Constrain the cellTextView.
cellTextView.topAnchor.constraintEqualToAnchor(superview.topAnchor).active = true
cellTextView.bottomAnchor.constraintEqualToAnchor(superview.bottomAnchor).active = true
cellTextView.leadingAnchor.constraintEqualToAnchor(superview.leadingAnchor).active = true
cellTextView.trailingAnchor.constraintEqualToAnchor(superview.trailingAnchor).active = true

答案 1 :(得分:0)

我认为你必须设置身高限制

  // Constrain the cellTextView.
    cellTextView.topAnchor.constraintEqualToAnchor(superview.topAnchor, constant: 0).active = true
    cellTextView.bottomAnchor.constraintEqualToAnchor(superview.bottomAnchor, constant: 0).active = true
    cellTextView.leadingAnchor.constraintEqualToAnchor(superview.leadingAnchor, constant: 0).active = true
    cellTextView.trailingAnchor.constraintEqualToAnchor(superview.trailingAnchor, constant: 0).active = true         

    cellTextView.sizeToFit()
    cellTextView.heightAnchor.constraintEqualToConstant(self.cellTextView.contentSize.height).active = true

您也可以尝试致电

    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()