斯威夫特 UITextView
Posted
技术标签:
【中文标题】斯威夫特 UITextView【英文标题】:Swift 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")
【问题讨论】:
Limit number of characters in 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 应该解释所有必要的内容。
【讨论】:
以上是关于斯威夫特 UITextView的主要内容,如果未能解决你的问题,请参考以下文章