2016-11-09 5 views
1

나는 많은 단어가 서로 나란히있는 UITextView이 있습니다. 사용자가 해당 화면을 시작했을 때 나는 몇 가지 단어를 강조 시작하려면, 예를 들면 :Swift에서 UITextView에서 하나씩 단어의 스타일을 어떻게 바꿀 수 있습니까?

one two three #four five six #seven eight nine ten 
eleven #twelve thirteen fourteen fifteen sixteen 
some other words #example test whatever #some thing 

다음 1 초 후에, 단어 four이 (스타일을 변경합니다 :

첫 번째는 그가 보는 것은 텍스트의 벽이다 색상), 그래서 그는 볼 것입니다 :

one two three #FOUR five six #seven eight nine ten 
eleven #twelve thirteen fourteen fifteen sixteen 
some other words #example test whatever #some thing 

다음 1 초 후에, 다른 단어가 강조 것이다 (이미 four 색 조인) :

one two three #FOUR five six #SEVEN eight nine ten 
eleven #twelve thirteen fourteen fifteen sixteen 
some other words #example test whatever #some thing 

등등. 따라서 몇 초 후에 사용자는 다음을 볼 수 있습니다.

one two three #FOUR five six #SEVEN eight nine ten 
eleven #TWELVE thirteen fourteen fifteen sixteen 
some other words #EXAMPLE test whatever #SOME thing 

다음 텍스트는 이와 같이 유지되어야합니다. 어떻게해야합니까?

단어를 반복하여 미리 정의 된 단어와 같은지 여부를 확인했지만 생각을하지 못했습니다. 어떻게 도와 드릴까요?

은 ===== 편집

그래서 나 자신에 대한 것들을 쉽게 내가 # 기호로 강조 단어를 표시하기로 결정하게합니다.

는 내가 텍스트 뷰에 #로 시작하는 모든 단어를 강조하기 위해 확장이 있습니다

extension UITextView { 

func formatTextInTextView() { 
    self.isScrollEnabled = false 
    let selectedRange = self.selectedRange 
    let text = self.text 
    let font = UIFont(name: "AppleSDGothicNeo-Light", size: 16.0) 
    let titleDict: NSDictionary = [NSFontAttributeName: font!] 
    // This will give me an attributedString with the desired font 
    let attributedString = NSMutableAttributedString(string: text!, attributes: titleDict as! [String : AnyObject]) 
    let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: []) 
    let matches = regex!.matches(in: text!, options: [], range: NSMakeRange(0, (text?.characters.count)!)) 
    for match in matches { 
     let matchRange = match.rangeAt(0) 

     let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor] 

     attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange) 
    } 
    self.attributedText = attributedString 
    self.selectedRange = selectedRange 
    self.isScrollEnabled = true 
} 
} 

을하지만 1 초 지연

+0

루프에 대한 아이디어는 올바른 방향입니다. 무언가를 시도하십시오. 적어도 몇 가지 기본적인 시도를 보여주는 관련 코드로 질문을 업데이트하십시오. 도움이 필요한 것이 무엇인지 명확하게 설명하십시오. – rmaddy

+0

@maddy, 나는 그것을 지적 해 주셔서 고마워요. – user3766930

+0

이 코드는 사용중인 정규 표현식으로 인해 모든 단어를 한 번에 강조 표시합니다. 강조 표시하려는 단어 목록 (배열)을 작성한 다음 해당 배열을 반복하는 방법이 필요합니다. 그런 다음 각 단어에 대해 해당 단어의 모든 일치 항목을 찾습니다. – rmaddy

답변

1

사용 타이머와 별도로 각 단어를 강조하는 방법을 모르겠어요. 대시는 속성에서 일치합니다. 강조되지 않은 속성 문자열을 속성에 숨 깁니다. 이제 타이머가 첫 번째 경기를 강조 표시하고 1 초 만에 다시 전화를 걸어 두 번째 경기까지 강조 표시하고 경기가 남아 있지 않을 때까지 반복하십시오.

func highlight (to index: Int = 0) { 
     guard index < matches.count else { 
      return 
     } 
     let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor] 
     let attributedString = NSMutableAttributedString(attributedString: storedAttributedString) 
     for i in 0..< index { 
      let matchRange = matches[i].rangeAt(0) 
      attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange) 
     } 
     self.attributedText = attributedString 
     let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in 
      self.highlight(to: index + 1) 
     } 
    } 
+0

Josh, 코드 작성을 시도했지만 많은 오류가 발생합니다. http://imgur.com/pOY6UYp 어떻게 해결할 수 있습니까? – user3766930

+1

NSMutableAttributedString()에 대한 위의 예제와 타이머의 종료에 대해 누락 된 인수 레이블을 추가했습니다. match에 대한 에러는 matches이어야하고 위의 코드에서와 같이 match = regex! .matches (in : text!, options : [], range : NSMakeRange (0, (text?). characters.count)!)) [String]이 아닌 [NSTextCheckingResult] 유형을 산출합니다. –

+0

감사합니다.attributedText = attributedString'은'attributedString'이 미확인 식별자라는 오류를 던졌습니다. (그리고 두 번째 것은 - if #available (iOS 10.0, *) {'을 Timer와 함께 줄에 추가해야했습니다. 현재 현재 // 이전 버전의 폴백 (Fallback) '으로 처리 할 수 ​​있습니까? - 처리 할 수있는 가장 좋은 옵션은 무엇입니까? – user3766930

관련 문제