【问题标题】:Expanding UITextView with UIButton instead of automatically based on content使用 UIButton 扩展 UITextView 而不是根据内容自动扩展
【发布时间】:2021-08-03 17:51:10
【问题描述】:

我有一个 UITextView,它嵌入在 UIView 中,而许多其他 UIView 都在 UIScrollView 中(本质上是一个表单)。我希望用户能够在该按钮下方单击并展开/折叠 textView,而不是 textView 自动随内容展开。

这是我所拥有的:

var textViewIsExpanded: Bool = false {
    didSet {
        if self.textViewIsExpanded {
            self.expandTextViewButton.isSelected = true
            guard self.myTextView.contentSize.height > 70 else { return }
            self.myTextView.isScrollEnabled = false
            self.myTextView.translatesAutoresizingMaskIntoConstraints = true
            self.myTextView.sizeThatFits(CGSize(width: self.scrollView.width - 24, height: CGFloat.greatestFiniteMagnitude))
        } else {
            self.expandTextViewButton.isSelected = false
            self.myTextView.isScrollEnabled = true
            self.myTextView.translatesAutoresizingMaskIntoConstraints = false
        }
    }
}

@IBAction func expandTextViewButtonTapped(_ sender: UIButton) {
    textViewIsExpanded.toggle()
}

我已经尝试用.sizeToFit() 代替.sizeThatFits(...),这很有效,但它随着高度调整了宽度,我只是想扩展/折叠高度。我猜这是正确实施 CGSize 和/或 IB 约束的问题,但我无法找到一个我想要的解决方案。

【问题讨论】:

    标签: ios swift xcode uitextview sizetofit


    【解决方案1】:

    首先,在真假之间切换.translatesAutoresizingMaskIntoConstraints 是个坏主意。

    您可能想要为您的文本视图提供 70 的高度约束...将其连接到 @IBOutlet...,然后在该约束上切换 .isActive

    第二,如果你只有一行文字,那么内容大小高度,可能是30,然后你调用

    textViewIsExpanded = true
    

    您的代码原样会将 textViewIsExpanded 设置为 true,但会将 .isScrollEnabled 保留为 true --- 所以它不会真正“扩展”。

    第三,您需要通过调用让自动布局知道您正在更改文本视图的大小调整行为:

    self.myTextView.invalidateIntrinsicContentSize()
    

    切换.isScrollEnabled之后。

    所以,为你的文本视图的高度约束添加和连接一个属性:

    @IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
    

    并尝试将您的代码更改为:

    var textViewIsExpanded: Bool = false {
        didSet {
            if self.textViewIsExpanded {
                // if contentSize.height is less-than 71
                //  reset to false
                if self.myTextView.contentSize.height < 71 {
                    self.textViewIsExpanded = false
                    return
                } else {
                    self.expandTextViewButton.isSelected = true
                    self.myTextView.isScrollEnabled = false
                    self.textViewHeightConstraint.isActive = false
                }
            } else {
                self.expandTextViewButton.isSelected = false
                self.myTextView.isScrollEnabled = true
                self.textViewHeightConstraint.isActive = true
            }
            self.myTextView.invalidateIntrinsicContentSize()
        }
    }
    

    【讨论】:

    • 嘿@DonMag,这立即完全按照我想要的方式工作。再次感谢您!
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2013-10-07
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多