我创建了一个UITextView
,但我希望每行只有一个单词,因此,每次我按空格破折号实际上都会返回文本。如何使空格键返回而不是实际间隔文本?另外,有没有一种方法可以记录每个单词以创建自定义数组?
这是我现在的代码:
@IBAction weak var wordView : UITextView!
@IBLabel weak var label : UILabel!
var words : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
endEditingTapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(endEditingTapGesture)
}
@IBAction func button(_ sender: Any) {
getArray()
}
func getArray() {
for _ in words {
words.append(wordView.text)
}
}
每次按下按钮时,按钮都应该在数组中添加单词...我不确定这是否是最好的解决方案...有帮助吗?
答案 0 :(得分:0)
尝试使用如下所示的textView委托方法用新行替换空间,
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//checks if new text is white space
if (text == " ") {
if (textView.text?.characters.last == "\n") {
// this will prevent multiple new lines
return false
}
let newText = (textView.text as NSString).replacingCharacters(in: range, with: "\n")
textView.text = newText
return false
}
return true
}
获取所有单词的数组
let allWords = yourTextView.text.components(separatedBy: "\n")
答案 1 :(得分:0)
如果您要使用委托,则可以使用委托。
这是示例代码。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let oldText = NSString(format: "%@", textView.text)
var newText = oldText.replacingCharacters(in: range, with: text)
newText = newText.replacingOccurrences(of: " ", with: "\n")
newText = newText.replacingOccurrences(of: "-", with: "\n")
textView.text = newText
let myWordArr = textView.text.components(separatedBy: "\n")
print(myWordArr)
return false
}
不要忘记设置委托。