Type 1
- The way to do it is to use NSAttributedString like this:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: label.attributedText];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 1)];
[label setAttributedText: text];
Type 2
- First of all initialize of you NSString and NSMutableAttributedString as below.
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
In ViewDidLoad
override func viewDidLoad() {
myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
// set label Attribute
labName.attributedText = myMutableString
super.viewDidLoad()
}
- MULTIPLE COLOR
Add the line code below in your ViewDidLoad to get multiple colors in a string.
var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))
Type 3
- By using following extension function, you can directly set a color attribute to an attributed string and apply the same on your label.
extension NSMutableAttributedString {
func setColorForText(textForAttribute: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
// Swift 4.2 and above
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
// Swift 4.1 and below
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
- Try above extension, using a label:
let label = UILabel()
label.frame = CGRect(x: 60, y: 100, width: 260, height: 50)
let stringValue = "stackoverflow"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textForAttribute: "stack", withColor: UIColor.black)
attributedString.setColorForText(textForAttribute: "over", withColor: UIColor.orange)
attributedString.setColorForText(textForAttribute: "flow", withColor: UIColor.red)
label.font = UIFont.boldSystemFont(ofSize: 40)
label.attributedText = attributedString
self.view.addSubview(label)
Type 4
- You can easily use html inside attributedText property of the UILabel to easily do various text formatting.
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
Type 5
- In my case, I needed to be able to set different colors/fonts within labels frequently so I made a UILabel extension using Krunal's NSMutableAttributedString extension.
func highlightWords(phrases: [String], withColor: UIColor?, withFont: UIFont?) {
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
for phrase in phrases {
if withColor != nil {
attributedString.setColorForText(textForAttribute: phrase, withColor: withColor!)
}
if withFont != nil {
attributedString.setFontForText(textForAttribute: phrase, withFont: withFont!)
}
}
self.attributedText = attributedString
}
- It can be used like this:
yourLabel.highlightWords(phrases: ["hello"], withColor: UIColor.blue, withFont: nil)
yourLabel.highlightWords(phrases: ["how are you"], withColor: UIColor.green, withFont: nil)
Type 6
- Here is an extension for NSMutableAttributedString, that add/set color on string/text.
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
- Now, try above extension with UILabel and see result
let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let red = "red"
let blue = "blue"
let green = "green"
let stringValue = "\(red)\n\(blue)\n&\n\(green)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red"
attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "blue"
attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "green"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
Type 7
- HTML문자열 데이터를 특성 문자열 텍스트로 변환
[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
} documentAttributes:nil error:nil];
- using NSMutableAttributedString from html string
NSHTMLTextDocumentTypeNSString *s = @"<p><a href='https://itunes.apple.com/us/app/xxxx/xxxx?mt=8'>https://itunes.apple.com/us/app/xxxx/xxxx?mt=8</a></p>";
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithData:[s dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ];
myUILabel.attributedText = text;
참고
- HTML to NSAttributedString
NSString *htmlString=[[NSString alloc]initWithFormat:@"<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"];
//Converting HTML string with UTF-8 encoding to NSAttributedString
NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding]
options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
documentAttributes: nil
error: nil ];
- NSAttributedString to HTML
//Dictionary to hold all the attributes of NSAttributed String
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
//Saving the NSAttributedString with all its attributes as a NSData Entity
NSData *htmlData = [attributedString dataFromRange:NSMakeRange(0, attributedString.length) documentAttributes:documentAttributes error:NULL];
//Convert the NSData into HTML String with UTF-8 Encoding
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
출처 :
https://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label
'개발 > iOS' 카테고리의 다른 글
Tcpdump 사용법 (0) | 2020.05.19 |
---|---|
APNs - 기능 및 유실 사례 (0) | 2020.05.18 |
OpenSSL Mac 연동 (0) | 2020.05.18 |
NSLog 출력 크기 제한 풀기 (0) | 2020.05.18 |
탈옥후 안정화 (0) | 2020.05.18 |