2016-07-24 2 views
3

특정 속성을 적용 할 텍스트 용어의 문자열을 포함하는 arrays이 있습니다. 코드 스니 피트는 다음과 같습니다.스위프트. 여러 인스턴스에 속성 추가

static var bold = [String]() 
static let boldAttribs = [NSFontAttributeName: UIFont(name: "WorkSans-Medium", size: 19)!] 
for term in bold { 
    atStr.addAttributes(boldAttribs, range: string.rangeOfString(term)) 
} 

이 기능은 단일 어구 또는 구문 용으로 유용합니다. 그러나 특정 용어의 첫 번째 사용에만 적용됩니다. 숫자 범위를 사용하지 않고 동일한 용어의 모든 인스턴스에 특성을 적용 할 수있는 방법이 있습니까? 예를 들어, 같은 문자열 내에서 "애니메이션 버튼"을 모두 굵게 사용하십시오.

편집 : 이것은 작동합니다.

// `butt2` is [String]() of substrings to attribute 
// `term` is String element in array, target of attributes 
// `string` is complete NAString from data 
// `atStr` is final 
for term in butt2 { 
    var pos = NSRange(location: 0, length: string.length) 
    while true { 
     let next = string.rangeOfString(term, options: .LiteralSearch, range: pos) 
     if next.location == NSNotFound { break } 

     pos = NSRange(location: next.location+next.length, length: string.length-next.location-next.length) 

     atStr.addAttributes(butt2Attribs, range: next) 
    } 
} 

답변

2

당신은 수치 범위에 의존 할 필요는 없지만, 루프에 의지해야합니까 :

// atStr is mutable attributed string 
// str is the input string 
atStr.beginEditing() 
var pos = NSRange(location: 0, length: atStr.length) 
while true { 
    let next = atStr.rangeOfString(target, options: .LiteralSearch, range: pos) 
    if next.location == NSNotFound { 
     break 
    } 
    atStr.addAttributes(boldAttribs, range: next) 
    print(next) 
    pos = NSRange(location: next.location+next.length, length: atStr.length-next.location-next.length) 
} 
atStr.endEditing() 
+0

이 유형의 범위 bpedit

+0

@bpedit 이것은 NSRange API가 조금 다르다는 것을 수정해야합니다. 컴파일러에서 "귀여운"내장 지원이 없습니다. – dasblinkenlight

+0

작동하지 않습니다. 'NSMutableString'은 '문자열의 범위'멤버가 없습니다. 나는 정말로 Swift'String'을'atstr'에'str'을 사용하고 싶습니다만, 나는 첫번 째 고비와 같은 변환 문제를 겪습니다. – bpedit

관련 문제