본문 바로가기
iOS/swift

attributedString

by 패쓰킴 2022. 12. 26.
728x90

텍스트 양쪽에 이미지 넣기

let attributedString = NSMutableAttributedString(string: "")
let leftImageAttachment = NSTextAttachment()
leftImageAttachment.image = UIImage(named: "quotes_left")
attributedString.append(NSAttributedString(attachment: leftImageAttachment))
attributedString.append(NSAttributedString(string: " \(msg!) "))
let rightImageAttachment = NSTextAttachment()
rightImageAttachment.image = UIImage(named: "quotes_right")
attributedString.append(NSAttributedString(attachment: rightImageAttachment))
messageLb.attributedText = attributedString

텍스트 속성 변경

let trafficAttributedString = NSMutableAttributedString(string: "여기에\n텍스트"
, attributes: [
.font: UIFont(name: "Pretendard-Bold", size: 18.0)!,
.foregroundColor: UIColor(white: 0.0, alpha: 1.0),
.kern: -0.9 ])

trafficAttributedString.addAttribute(.font, value: UIFont(name: "Pretendard-Regular",
size: 18.0)!,
range: NSRange(location: 0, length: 6)
)
trafficLb.attributedText = trafficAttributedString

텍스트 append

NSMutableAttributedString *menuAttributeStr = [NSMutableAttributedString new];
NSMutableAttributedString *barAttributeStr = [[NSMutableAttributedString alloc] initWithString:@"  l  " attributes:barAttribute];

[menuAttributeStr appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"메뉴" attributes:menuAttribute]];
[menuAttributeStr appendAttributedString:barAttributeStr];

menuLB.attributedText = menuAttributeStr;

 

특정 문자만 컬러 바꾸기

iOS

let range = ("분류 *" as NSString).range(of: "*")
let categoryAttributedString = NSMutableAttributedString.init(string: "분류 *")
categoryAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
categoryTitleLB.attributedText = categoryAttributedString

결과:  분류 *

 

Objective - C

참조: https://roniruny.tistory.com/144

NSMutableAttributedString * result = [[NSMutableAttributedString alloc]initWithString:바꾸려는 문자를 포함하는 문자열];
[result addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[바꾸려는 문자를 포함하는 문자열 rangeOfString:바꾸려는 문자]];
LB.attributedText = result;

 

밑줄 귿기

let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]
let underlineAttributedString = NSAttributedString(string: 밑줄 그을 문자열, attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString

결과: 문자열

 

NSMutableAttributedString -> String

attributedText.string
728x90

'iOS > swift ' 카테고리의 다른 글

숫자 다루기  (1) 2023.11.07
Array  (0) 2022.12.21
String  (0) 2022.09.22
진법 변환  (0) 2022.08.31
Alamofire timeout set(Swift5)  (0) 2022.08.25

댓글