隐藏在 StackView 中的 TextView 占位符被截断

问题描述

我有一个放置在 UIView 中的 TextView,然后将其放置在 StackView 中,如下所示:

- UIStackView
    - UIView
        - UITextView

我还为 extension 查找了一个自定义 UITextView,它允许我在文本视图中添加占位符:

import UIKit

extension UITextView {

    private class PlaceholderLabel: UILabel { }

    private var placeholderLabel: PlaceholderLabel {
        if let label = subviews.compactMap( { $0 as? PlaceholderLabel }).first {
            return label
        } else {
            let label = PlaceholderLabel(frame: .zero)
            label.font = font
            addSubview(label)
            
            return label
        }
    }

    @IBInspectable
    var placeholder: String {
        get {
            return subviews.compactMap( { $0 as? PlaceholderLabel }).first?.text ?? ""
        }
        set {
            let placeholderLabel = self.placeholderLabel
            placeholderLabel.text = newValue
            placeholderLabel.numberOfLines = 0
            let width = frame.width - textContainer.lineFragmentPadding * 2
            let size = placeholderLabel.sizeThatFits(CGSize(width: width,height: .greatestFiniteMagnitude))
            placeholderLabel.frame.size.height = size.height
            placeholderLabel.frame.size.width = width
            placeholderLabel.frame.origin = CGPoint(x: textContainer.lineFragmentPadding,y: textContainerInset.top)

            textStorage.delegate = self
        }
    }
    
    @IBInspectable
    var placeholderColor: UIColor? {
        get {
            self.placeholderColor
        }
        
        set {
            placeholderLabel.textColor = newValue
        }
    }

}

extension UITextView: NSTextStorageDelegate {

    public func textStorage(_ textStorage: NSTextStorage,didProcessEditing editedMask: NSTextStorage.Editactions,range editedRange: NSRange,changeInLength delta: Int) {
        if editedMask.contains(.editedCharacters) {
            placeholderLabel.isHidden = !text.isEmpty
        }
    }

}

但是,当我在堆栈视图中将 UIView 设置为 hidden 时,占位符在 UI​​View 可见后被截断:

enter image description here

如果我将 UIView 设置为 hidden,它显示正常:

enter image description here

我发现当我将它设置为 UIView 时,堆栈视图中 hidden 的宽度会发生变化:

enter image description here

如您所见,隐藏时不再是全角。与 UITextView 相同:

enter image description here

我怀疑是在显示 UIView 时未正确重置占位符文本的约束。

我该怎么做才能解决这个问题?

解决方法

好像 -

  1. 即使 UIStackView 通过在您标记 UIView.width/height == 0 时使 .isHidden = true 做正确的事情
  2. UIView 内的内容在其边界外仍然可见。

您可以尝试为包含 clipsToBounds = trueUIView 设置 UITextView

- UIStackView
    - UIView ///// Try setting `clipsToBounds = true` for this one
        - UITextView