将TextView限制为swift 2中的特定行数

时间:2016-02-01 09:43:42

标签: ios swift uitextview

我需要将textview限制为只有6行。如何将textview限制为6行?不管怎样,我已经设置了50个字符的字符限制。

2 个答案:

答案 0 :(得分:4)

这很难实现。试试下面的代码

inputTextView.textContainer.maximumNumberOfLines = 6
inputTextView.textContainer.lineBreakMode = .ByWordWrapping

答案 1 :(得分:0)

对于Swift 4来说,它没有任何错误就可以工作:

$data = array(
  0 => array(
            'vrl' => 'asd',
            'cat' => 'WED',
            'id' => 'WED05',
            'created' => '2018-05-10 11:29:45'
        ),
    1 => array
        (
            'vrl' => 'asdfasdf',
            'cat' => 'WED',
            'id' => 'WED06',
            'created' => '2019-02-26 15:59:53',
        ),
    2 => array
        (
            'vrl' => 'asdfasdf',
            'cat' => 'WED',
            'id' => 'WED06',
            'created' => '2010-05-27 15:59:53',
        ),
    3 => array
        (
            'vrl' => 'awef',
            'cat' => 'WED',
            'id' => 'WED07',
            'created' => '2010-05-07 15:59:53',
        )
);

,如果您还想限制字符,则:

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
}

不要忘记在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