【问题标题】:Swift UITextView斯威夫特 UITextView
【发布时间】:2014-12-03 15:15:47
【问题描述】:

我正在尝试创建一个 UiTextView,它只能输入 50 个字符,长度不应超过两行,当按下返回时关闭键盘。基于许多 stackover 尝试了各种方法,但似乎没有一个可以解决问题。不确定它必须如此难以做到。任何帮助将不胜感激

目前正在使用

    func textView(textView: UITextView!, shouldChangeTextInRange: NSRange, replacementText: NSString!){
if let range = text.rangeOfCharacterFromSet(NSCharacterSet.newlineCharacterSet()) {
        println("start index: \(range.startIndex), end index: \(range.endIndex)")
    }
    else {
        println("no data")
    }
}

【问题讨论】:

标签: swift ios8 uitextview


【解决方案1】:

我不确定您所说的“长度不应超过两行”是什么意思,但我可以向您展示如何实现该委托方法以将文本输入限制为 50 个或更少的字符。

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    // range contains the range of text that is currently selected, this will be overwritten after this method returned true. If length is 0 nothing will be overwritten
    // text contains the replacement text, might be the empty string "" which indicates deletion

    // current text content of textView must be converted from String to NSString 
    // because stringByReplacingCharactersInRange(...) is a method on NSString
    let currentText = textView.text as NSString

    // do the changes that would happen if this method would return true
    let proposedText = currentText.stringByReplacingCharactersInRange(range, withString: text)
    if countElements(proposedText) > 50 {
        // text would be longer than 50 characters after the changes are applied
        // so ignore any input and don't change the content of the textView
        return false
    }
    // go ahead and change text in the textView
    return true
}

内联 cmets 应该解释所有必要的内容。

【讨论】:

    猜你喜欢
    • 2017-07-22
    • 2017-03-24
    • 1970-01-01
    • 2016-02-08
    • 2017-11-13
    • 2015-08-19
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多