在数组中快速移动texview中的所有字符

问题描述

用户键入内容时,我正在尝试获取数组中的所有字符。

以我的代码;当我键入“ hello”并打印时,我得到:

arrRegular: [“h”]
arrRegular: [“e”]
arrRegular: [“l”]
arrRegular: [“l”]
arrRegular: [“o”]

如何将所有字符都排列成一个数组,例如[“ h”,“ e”,“ l”,“ l”,“ o”]

我的代码

func textView(_ textView: UITextView,shouldChangeTextIn range: NSRange,replacementText text: String) -> Bool {
    
    var arrRegular = [String]()
    var arrBold = [String]()
    var arrCombined = [String]()
    
    if boldFont == false {
        
        arrRegular.append(text)
        
    } else {
        
        arrBold.append(text)
    }
    
    arrCombined.append(contentsOf: arrRegular)
    arrCombined.append(contentsOf: arrBold)
    
    print(arrCombined)
    
    return true
}

解决方法

您的var var arr = [String]()是本地变量,并且在每次调用shouldChangeTextIn时都会创建该变量,而每次调用该字符都是

您需要

 let arr = Array(textView.text!)

let arr = textView.text.map { "\($0)" }
print(arr)
,
let text = textView.text ?? ""
let array = Array(text)