Develop
2024.12.14 01:35
[ios] UILabel with two different color text
조회 수 1026 댓글 0
# Usage (Swift)
// Sample private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.lightGray label.font = UIFont.systemFont(ofSize: 16) label.numberOfLines = 0 return label }() let red = "red" let blue = "blue" let green = "green" let stringValue = "\(red)\n\(blue)\n&\n\(green)" let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red" attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "blue" attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "green" attributedString.setFont(font: UIFont.systemFont(ofSize: 24), forText: green) label.attributedText = attributedString
# Extension Sample (Swift)
// Extension. extension NSMutableAttributedString { func setColor(color: UIColor, forText stringValue: String) { let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range) } func setFont(font: UIFont, forText stringValue: String) { let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) self.addAttribute(NSAttributedString.Key.font, value: font, range: range) } }
# Example (Objective-C)
// Objective-C Example. NSString *title = @"I am a great student"; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title]; NSRange targetRange = [title rangeOfString:@"great"]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:targetRange]; UILabel *titleLabel = [[UILabel alloc] init]; titleLabel.font = [UIFont systemFontOfSize:16]; titleLabel.textColor = [UIColor lightGrayColor]; titleLabel.numberOfLines = 0; titleLabel.lineBreakMode = NSLineBreakByWordWrapping; titleLabel.textAlignment = NSTextAlignmentLeft; [titleLabel setAttributedText:attributedString];
-
[ios] UILabel with two different color text
-
[ios] 배경에 Gradient 적용하기 (CAGradientLayer)
-
Brave Browser for Debian, Ubuntu, Mint
-
Ubuntu Desktop RDP Setup - 24.04 LTS
-
원어민이 매일 쓰는 일상표현 150개
-
영어. 반드시 외워야 할 문장 패턴 100개
-
[swift] UIView에서 subview 찾기
-
네트워크 용어 정리
-
[macos] How to Fix ‘You Shut Down Your Computer Because of a Problem’
-
[ios] 여러 버전의 Xcode 사용하기
-
[ios] Pod 특정 버전 설치하고 사용하기
-
맥에서 포트 확인하고 닫기 (mac)