如何删除空 UITextView 上的空白文本容器

How to remove the blank text container on empty UITextView

我已经将属性 textContainerInsetlineFragmentPadding 设置为零,如在此代码中所见,这要归功于通过此 SO answer 删除了填充和边距。

// this is inside a UITextView Subclass
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.textContainerInset = .zero
    self.textContainer.lineFragmentPadding = 0
}

下面是 UITextView 有文字时的呈现方式

这里是多行

这是它在没有文本的情况下的呈现方式

如果UITextView的文本为空,是否可以将高度设为0

编辑:

  1. UITextView 没有使用约束,我不打算设置高度约束,因为我希望 UITextView 根据 正文被设置进去

  2. 这是 UITableViewCell 中的 isScrollEnabled = false UITextView,它会根据从 api 服务器获取的数据自动调整大小。

关于:

语言:Swift3.2

IDE: Xcode 9.2

试试这个代码:

CGSize sizeThatFitsTextView = [TextView sizeThatFits:CGSizeMake(TextView.frame.size.width, MAXFLOAT)];
TextViewHeightConstraint.constant = sizeThatFitsTextView.height;

您可以为 TVw 设置两个高度限制。一个具有您想要的高度,另一个具有 0 高度和较低的优先级。

然后在 TextView 的委托上执行如下操作:

func textViewDidChange(_ textView: UITextView) {
    constraint.isActive = textView.text.count != 0
}

感谢 uhuru 的回答,我已经制定了一个不需要太多修改的代码的答案。

首先,我以编程方式为 UITextView 设置了高度限制。

// outside the scope
var contentTextViewConstraint: NSLayoutConstraint?

// inside awakeFromNib
self.contentTextViewConstraint = NSLayoutConstraint(
    item: self.lblContent,
    attribute: NSLayoutAttribute.height,
    relatedBy: NSLayoutRelation.equal,
    toItem: nil,
    attribute: NSLayoutAttribute.notAnAttribute,
    multiplier: 1,
    constant: 0)
self.contentTextViewConstraint?.isActive = false

然后activate/deactivate约束取决于String

// inside the setup
let contentText: String = model.contentText
self.tvContent.text = contentText
self.contentTextViewConstraint?.isActive = contentText.isEmpty

这可能是 UITextView 的错误。尝试遵循代码:

- (CGSize)intrinsicContentSize {
    CGSize size = [super intrinsicContentSize];
    if ((size.width < FLT_EPSILON || size.height < FLT_EPSILON) && self.textStorage.string.length == 0) {
        return CGSizeZero;
    } else {
        return size;
    }
}

另一种可能的解决方案是在 InterfaceBuilder 中为 height == 0 添加约束,将其设置为 isActive == false 并为其提供自定义标识符。

Activate/deactivate 它在代码中需要时使用 :

textView.constraints.first { [=12=].identifier == "theConstrainIdentifier" }?.isActive = false // or true