오랫동안 나를 괴롭 히고 있습니다. 제목에서 알 수 있듯이, 나는 다양한 색상으로 특정 단어를 강조하는 아이디어가있는 다른 방법을 찾지 못합니다. 예를 들어, "hello", "awesome", "hungry", "sky"... 등의 단어가 포함 된 배열이있는 경우 그런 다음 아래 코드에서 하나의 색상으로 배열 안의 단어를 강조 표시하고 NSBackgroundColorAttributeName
으로 설정합니다. 지금까지 실패한 나의 가장 좋은 해결책은 동일한 방법을 여러 개 생성하는 것이 었습니다. 그래서 몇 가지 방법을 만들고 각 방법에 배열을 입력하고 각기 다른 색상을 변경했습니다.NSAtrributedString을 사용하여 UITextVIew에서 여러 색상의 단어를 어떻게 강조 할 수 있습니까?
내 TextView에 입력 된 단어가 파란색으로 변했습니다. 다른 배열의 다른 단어가 내 TextView에 입력 된 후 새로 입력 한 단어는 빨간색이되었지만 이전 단어는 더 이상 강조 표시되지 않았습니다. 다른 배열의 모든 단어를 다르게 강조 표시하고 싶습니다. 나는 그들의 색깔이 사라지 길 바라지 않는다. 나는이 아이디어를 1 주일 동안 생각해 낼 수 없다. 이걸 좀 도와 주실 래요?
func highlightColors(type: [String]){
let attrStr = NSMutableAttributedString(string: myTextView.text)
let inputLength = attrStr.string.characters.count
let searchString : NSArray = NSArray.init(array: type)
for i in 0...searchString.count-1 {
let string : String = searchString.object(at: i) as! String
let searchLength = string.characters.count
var range = NSRange(location: 0, length: attrStr.length)
while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: string, options: [], range: range)
if (range.location != NSNotFound) {
coloredStringArray.append(string)
attrStr.addAttribute(NSBackgroundColorAttributeName, value: UIColor.blue, range: NSRange(location: range.location, length: searchLength))
attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20), range: range)
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
myTextView.attributedText = attrStr
myTextView.font = UIFont(name: "times new roman", size: 20.0)
}
}
}
}
덕분에, 나는 그것을 구현합니다. 사실, 나는 UserDefaults의 배열을 가지고있다. 아직도 작동합니까? –
안녕하세요, 효과가있었습니다. 그러나 배열의 단어 중 하나가 반복적으로 사용되면 같은 단어의 두 번째 단어는 더 이상 강조 표시되지 않습니다. 어떻게 모든 단어를 강조 표시합니까? –
음, 작동하지 않습니다 ... –