【问题标题】:Swift 4: How to set only one word per row in an UITextView and create an array with each rowSwift 4:如何在 UITextView 中每行只设置一个单词并为每行创建一个数组
【发布时间】:2019-03-01 09:01:59
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift uiview uitextview


    【解决方案1】:

    如果您正在使用委托,则可以使用委托。

    这里是示例代码。

    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
    }
    


    别忘了设置委托。

    【讨论】:

    • 哎呀!工作正常!只是一个问题,如果我想在我的课堂上调用 myWordArr 怎么办(我把你的代码放在一个扩展中)?
    【解决方案2】:

    尝试使用下面的 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")
    

    【讨论】:

    • 我尝试添加一个扩展:extension ViewController : UITextViewDelegate{//your code inside} 但它说'characters'已被弃用:请直接使用字符串或子字符串。所以我现在尝试将其更改为 substring.text 但它不接受它。无论如何我尝试运行它,但它仍然增加了一个空格,我该怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2011-04-14
    • 2021-10-14
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多