iOS 중간 글자 크기, 색상 변경하기 NSMutableAttributedString
글자 중간중간의 색상, 크기, 하이퍼링크를 주고 싶다면 NSMutableAttributedString 클래스를 사용하면 된다.
아래 코드를 사용하면 다음과 같은 화면이 나온다.
NSMutableAttributedString *stringAtterbuted = [[NSMutableAttributedString alloc] initWithString:@"가나다라 마바사아 아자차카 타파하"];
[stringAtterbuted addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:20.0]
range:NSMakeRange(0, 3)];
[stringAtterbuted addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,3)];
[stringAtterbuted addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(4, 3)]; //UITextLable과 UITextField는 지원하지 않는다.
[stringAtterbuted addAttribute: NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range: NSMakeRange(7,3)]; //삭제 표시 라인
[stringAtterbuted addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:8.0f]
range:NSMakeRange(12, 3)];
[stringAtterbuted addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(12, 3)];
[stringAtterbuted addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(15, 3)]; //언더라인
textViewString.editable = NO;
textViewString.dataDetectorTypes = UIDataDetectorTypeLink;
[labelString setAttributedText:stringAtterbuted]; // 텍스트 라벨
[textViewString setAttributedText:stringAtterbuted]; // 텍스트 뷰
하이퍼링크의 경우 현재 버전(iOS 9버전)에서는 UITextLabel과 UITextField는 지원하지 않고 있으며 UITextView에서 수정이 안되도록 editable 속성을 NO, 그리고 dataDetectorTypes을 UIDataDetectorTypeLink타입으로 변경 해 주어야 한다. (스토리보드나 xib파일에서도 변경 할 수 있다.)
여기서 예시에 사용한 속성은
NSFontAttributeName : 폰트와 글자 사이즈 변경
NSForegroundColorAttributeName : 글자 색상 변경
NSLinkAttributeName : 하이퍼링크
NSStrikethroughStyleAttributeName : 삭제 표시 라인
NSUnderlineStyleAttributeName : 언더라인
이며 사용 가능한 속성은 아래와 같다.