OGeek|极客世界-中国程序员成长平台

标题: ios - 当文本达到 N 行时开始滚动的 UITextView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:59
标题: ios - 当文本达到 N 行时开始滚动的 UITextView

我开始在聊天应用中实现文本输入,我想知道启用滚动的 UITextView 的标准行为绝对不符合预期。
我只想在 WhatsApp 之类的聊天中完成。当文本达到 N,例如 5 行时,会出现滚动条并且文本容器开始滚动。我写了这样的代码,但它不起作用。 正如我认为需要计算文本容器中的行并制作内容插入或类似的东西。

   func textViewDidChange(_ textView: UITextView) {
        let fixedWidth = myTextView.frame.size.width
        myTextView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
        let newSize = myTextView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
        var newFrame = myTextView.frame
        let oldFrame = myTextView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        myTextView.frame = newFrame  
        let shift = oldFrame.height - newFrame.height
        textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: shift, right: 0)
        textView.scrollIndicatorInsets = textView.contentInset
        textView.scrollRangeToVisible(textView.selectedRange)
    }

而myTextView被指定为:

let myTextView : UITextView = {
        let textView = UITextView()
        textView.translatesAutoresizingMaskIntoConstraints =  false
        textView.isScrollEnabled = false
        textView.textContainer.maximumNumberOfLines = 5
        textView.textContainer.lineBreakMode = .byWordWrapping
        textView.inputAccessoryView = UIView()
        return textView
    }()



Best Answer-推荐答案


不是基于行数,而是基于用户定义的高度。你会在这里找到你的答案: https://stackoverflow.com/a/51235517/10115072

关于ios - 当文本达到 N 行时开始滚动的 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42235360/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4