iOS의 단일 레이블에 두 개 또는 세 개의 글꼴 색상을 사용하는 방법이 있습니까?
“hello, how are you”라는 텍스트가 예로 사용 된 경우 “hello”는 파란색이고 “how are you”는 녹색이됩니다.
이것이 가능합니까, 여러 레이블을 만드는 것보다 쉬운 것 같습니까?
답변
먼저 NSString 및 NSMutableAttributedString 을 아래와 같이 초기화하십시오 .
var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
에 있는 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()
}
산출
여러 색상
ViewDidLoad에 아래 줄 코드를 추가하여 문자열에 여러 색상을 가져옵니다.
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))
여러 색상 출력
스위프트 4
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))
답변
@Hems Moradiya 용
let attrs1 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.greenColor()]
let attrs2 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.whiteColor()]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.appendAttributedString(attributedString2)
self.lblText.attributedText = attributedString1
스위프트 4
let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.white]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1
스위프트 5
let attrs1 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.green]
let attrs2 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.white]
let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)
let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)
attributedString1.append(attributedString2)
self.lblText.attributedText = attributedString1
답변
스위프트 4
다음 확장 기능을 사용하여 속성 문자열에 색상 속성을 직접 설정하고 레이블에 동일하게 적용 할 수 있습니다.
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)
}
}
레이블을 사용하여 위의 확장을 시도하십시오.
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)
결과:
답변
Swift 4에 대한 업데이트 된 답변
UILabel의 attributeText 속성 내에서 html을 쉽게 사용하여 다양한 텍스트 서식을 쉽게 수행 할 수 있습니다.
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")
}
Swift 2에 대한 업데이트 된 답변
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
label.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
답변
여기 Swift 5에 대한 솔루션
let label = UILabel()
let text = NSMutableAttributedString()
text.append(NSAttributedString(string: "stack", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]));
text.append(NSAttributedString(string: "overflow", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray]))
label.attributedText = text
답변
중고 rakeshbs 의 대답은 스위프트 2의 확장을 만들 수 있습니다 :
// StringExtension.swift
import UIKit
import Foundation
extension String {
var attributedStringFromHtml: NSAttributedString? {
do {
return try NSAttributedString(data: self.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch _ {
print("Cannot create attributed String")
}
return nil
}
}
용법:
let htmlString = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>"
label.attributedText = htmlString.attributedStringFromHtml
또는 한 줄짜리도
label.attributedText = "<font color=\"red\">This is </font> <font color=\"blue\"> some text!</font>".attributedStringFromHtml
확장 기능의 좋은 점은 전체 응용 프로그램 .attributedStringFromHtml
에서 모든 속성에 대한 속성 이 있다는 것 String
입니다.
답변
나는 이것을 좋아했다
let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFontOfSize(15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFontOfSize(25)]
let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)
let combination = NSMutableAttributedString()
combination.appendAttributedString(partOne)
combination.appendAttributedString(partTwo)