首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将TextView限制在一定数量的number 2中

将TextView限制在一定数量的number 2中
EN

Stack Overflow用户
提问于 2016-02-01 09:43:41
回答 2查看 5.1K关注 0票数 4

我需要限制我的文本视图只有6行。如何将文本视图限制为6行?我已经设置了一些字符限制50个字符无论如何。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-01 10:13:25

要做到这一点很少简单。试试下面的代码

代码语言:javascript
复制
inputTextView.textContainer.maximumNumberOfLines = 6
inputTextView.textContainer.lineBreakMode = .ByWordWrapping
票数 10
EN

Stack Overflow用户

发布于 2019-02-28 11:24:55

对于斯威夫特4来说,这个方法没有任何错误:

代码语言:javascript
复制
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
    let newLines = text.components(separatedBy: CharacterSet.newlines)
    let linesAfterChange = existingLines.count + newLines.count - 1
    return linesAfterChange <= textView.textContainer.maximumNumberOfLines
}

如果您还想限制字符:

代码语言:javascript
复制
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
        let newLines = text.components(separatedBy: CharacterSet.newlines)
        let linesAfterChange = existingLines.count + newLines.count - 1
        if(text == "\n") {
            return linesAfterChange <= textView.textContainer.maximumNumberOfLines
        }

        let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
        let numberOfChars = newText.count
        return numberOfChars <= 30 // 30 characters limit
    }
}

不要忘记在viewDidLoad中添加您希望限制的行数

代码语言:javascript
复制
txtView.textContainer.maximumNumberOfLines = 2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35127261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档