ios - swift 4 : How to set only one word per row in an UITextView and create an array with each row

标签 ios swift uiview uitextview

我创建了一个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)
    }
}

每次按下按钮时,该按钮都应该向数组添加单词...我不确定这是最好的解决方案...有什么帮助吗?

最佳答案

如果您正在使用委托(delegate)来获取输入,则可以使用委托(delegate)。

这是示例代码。

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
}


不要忘记设置委托(delegate)。

关于ios - swift 4 : How to set only one word per row in an UITextView and create an array with each row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941156/

相关文章:

ios - iOS 的屏幕截图

ios - UIViewAnimationOptionBeginFromCurrentState 基本动画的意外行为

json - 当使用 Alamofire 和 SwiftyJSON 从 URL 获取 JSON 时,链接返回 nil 并使我的应用程序崩溃

objective-c - 我想在 iPad 上刷新 UIImageview,我该怎么做?

iphone - 同步 UIView 动画

ios - 如何在快速的一键操作中切换两个值

ios - AppDelegate 没有可见接口(interface)声明选择器

ios - 如何在 iOS 9.1 设​​备上运行 swift 1.2 代码?

swift - 相等运算符重载未按预期工作

iphone - 如何让处理程序重复 UIView animateWithDuration?