【问题标题】:TextView placeholder being cut off when hidden inside StackView隐藏在 StackView 中时,TextView 占位符被切断
【发布时间】:2021-08-25 23:16:21
【问题描述】:

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

- UIStackView
    - UIView
        - UITextView

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

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 可见后被切断:

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

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

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

我怀疑在显示 UIView 时,占位符文本的约束没有被正确重置。

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

【问题讨论】:

    标签: ios swift xcode constraints


    【解决方案1】:

    好像-

    1. 即使UIStackView 做正确的事情是在你标记.isHidden = true 时将UIView.width/height == 0 标记为.isHidden = true
    2. UIView 中的内容在其边界之外仍然可见。

    您可以尝试将clipsToBounds = true 设置为您的UIView,其中包含UITextView

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

    【讨论】:

    • 对不起,这不能回答我的具体问题。它很好地隐藏了视图。问题是它没有正确显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2014-05-20
    • 2013-02-07
    • 2018-03-19
    • 2014-02-24
    相关资源
    最近更新 更多