NSA 특성 문자열을 사용하여 문자열 색상을 변경하시겠습니까?
슬라이더 값을 기준으로 다음 문자열을 표시하는 설문 조사용 슬라이더가 있습니다. "매우 잘못됨, 잘못됨, 좋아요, 좋아요, 아주 좋아요.
슬라이더의 코드는 다음과 같습니다.
- (IBAction) sliderValueChanged:(UISlider *)sender {
scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
NSArray *texts=[NSArray arrayWithObjects:@"Very Bad", @"Bad", @"Okay", @"Good", @"Very Good", @"Very Good", nil];
NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
self.scanLabel.text=[texts objectAtIndex:sliderValue];
}
저는 "Very Bad"가 빨간색, "Bad"가 주황색, "Okay"가 노란색, "Good"가 녹색이었으면 좋겠습니다.
사용 방법을 이해할 수 없습니다.NSAttributedString
이 일을 끝내기 위해.
사용할 필요가 없습니다.NSAttributedString
필요한 것은 적절한 라벨이 있는 간단한 라벨입니다.textColor
또한 이 간단한 솔루션은 iOS 6뿐만 아니라 iOS의 모든 버전에서 작동합니다.
하지만 불필요하게 사용하고 싶다면,NSAttributedString
다음과 같은 작업을 수행할 수 있습니다.
UIColor *color = [UIColor redColor]; // select needed color
NSString *string = ... // the string to colorize
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
self.scanLabel.attributedText = attrStr;
다음과 같은 방법 사용(컴파일러 선택 안 함)
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different
NSArray *colors=@[[UIColor redColor],
[UIColor redColor],
[UIColor yellowColor],
[UIColor greenColor]
];
[string addAttribute:NSForegroundColorAttributeName
value:colors[sliderValue]
range:range];
[self.scanLabel setAttributedText:texts[sliderValue]];
Swift 4/5에서:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString
Swift 3에서:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString
즐거운 시간 되세요.
Swift 5의 경우:
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
Swift 4의 경우:
var attributes = [NSAttributedStringKey: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
Swift 3의 경우:
var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
생성할 수 있습니다.
NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];
또는 사용자 지정 특성을 범위에 적용합니다.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }];
[attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];
사용 가능한 특성: NSA 속성 문자열 키
업데이트:
스위프트 5.1
let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]
let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))
스위프트 4와 함께라면,NSAttributedStringKey
라는 정적 속성이 있습니다.foregroundColor
.foregroundColor
에는 다음과 같은 선언이 있습니다.
static let foregroundColor: NSAttributedStringKey
이 특성의 값은 다음과 같습니다.
UIColor
물건.이 속성을 사용하여 렌더링하는 동안 텍스트 색상을 지정합니다.이 속성을 지정하지 않으면 텍스트가 검은색으로 렌더링됩니다.
다음 Playground 코드는 텍스트 색상을 설정하는 방법을 보여줍니다.NSAttributedString
의 예.foregroundColor
:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
아래 코드는 가능성을 보여줍니다.UIViewController
에 의존하는 구현NSAttributedString
의 텍스트 및 텍스트 색상을 업데이트하기 위해UILabel
a부터UISlider
:
import UIKit
enum Status: Int {
case veryBad = 0, bad, okay, good, veryGood
var display: (text: String, color: UIColor) {
switch self {
case .veryBad: return ("Very bad", .red)
case .bad: return ("Bad", .orange)
case .okay: return ("Okay", .yellow)
case .good: return ("Good", .green)
case .veryGood: return ("Very good", .blue)
}
}
static let minimumValue = Status.veryBad.rawValue
static let maximumValue = Status.veryGood.rawValue
}
final class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var slider: UISlider!
var currentStatus: Status = Status.veryBad {
didSet {
// currentStatus is our model. Observe its changes to update our display
updateDisplay()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Prepare slider
slider.minimumValue = Float(Status.minimumValue)
slider.maximumValue = Float(Status.maximumValue)
// Set display
updateDisplay()
}
func updateDisplay() {
let attributes = [NSAttributedStringKey.foregroundColor : currentStatus.display.color]
let attributedString = NSAttributedString(string: currentStatus.display.text, attributes: attributes)
label.attributedText = attributedString
slider.value = Float(currentStatus.rawValue)
}
@IBAction func updateCurrentStatus(_ sender: UISlider) {
let value = Int(sender.value.rounded())
guard let status = Status(rawValue: value) else { fatalError("Could not get Status object from value") }
currentStatus = status
}
}
그러나 실제로 사용할 필요는 없습니다.NSAttributedString
그러한 예를 위해 그리고 간단히 의지할 수 있습니다.UILabel
의text
그리고.textColor
특성.따라서, 당신은 당신의 것을 교체할 수 있습니다.updateDisplay()
다음 코드로 구현:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}
Swift 5.2용 업데이트
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = UIColor.blue
let attributedString = NSAttributedString(string: "Very Bad",
attributes: attributes)
label.attributedText = attributedString
스위프트행 라이너 1개:
NSAttributedString(string: "Red Text", attributes: [.foregroundColor: UIColor.red])
나는 일을 쉽게 만드는 것을 좋아합니다, 이것을 시도해 보세요.
-(NSArray *) reArrangeArrays:(NSArray *)iObjects {
NSMutableArray *Words = [[NSMutableArray alloc] init];
NSMutableArray *Colors = [[NSMutableArray alloc] init];
CFIndex OneThree = 0;
CFIndex TwoFour = 1;
for (CFIndex iCounter = 0; iCounter < iObjects.count; iCounter ++) {
[Words addObject:[iObjects objectAtIndex:OneThree]];
[Colors addObject:[iObjects objectAtIndex:TwoFour]];
OneThree = OneThree + 2;
TwoFour = TwoFour + 2;
if (OneThree > iObjects.count || TwoFour > iObjects.count)
break;
}
return @[[NSArray arrayWithArray:Words],[NSArray arrayWithArray:Colors]];
}
+(NSMutableAttributedString *) OriginalText:(NSString *)OriginalText WordsAndColors:(NSArray *)WordsAndColors TheRestOfTheTextColor:(UIColor *)TheRestColor {
NSArray *Text = [[self.alloc reArrangeArrays:WordsAndColors] objectAtIndex:0];
NSArray *Color = [[self.alloc reArrangeArrays:WordsAndColors] objectAtIndex:1];
NSMutableAttributedString *MutableAttString = [[NSMutableAttributedString alloc] initWithString:OriginalText attributes:@{NSForegroundColorAttributeName : TheRestColor}];
NSString *text = OriginalText;
if (OriginalText != nil) {
for (NSUInteger Counter = 0; Counter < Color.count; Counter ++) {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"(%@)",[Text objectAtIndex:Counter]] options:kNilOptions error:nil];
NSRange range = NSMakeRange(0 ,text.length);
[regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange subStringRange = [result rangeAtIndex:0];
[MutableAttString addAttribute:NSForegroundColorAttributeName value:[Color objectAtIndex:Counter] range:subStringRange];
}];
}
}
return MutableAttString;
}
그리고 이것이 사용 방법입니다.
NSString *Text = @"Made by @CrazyMind90";
NSMutableAttributedString *AttriString = [ViewController OriginalText:Text
WordsAndColors:@[
@"Made",UIColor.redColor,
@"by",UIColor.yellowColor,
@"@CrazyMind90",UIColor.blueColor,
]
TheRestOfTheTextColor:UIColor.whiteColor];
//Not TextView.text BUT TextView.attributedText
TextView.attributedText = AttriString;
..
언급URL : https://stackoverflow.com/questions/14287386/change-string-color-with-nsattributedstring
'programing' 카테고리의 다른 글
ClassNotFoundException: org.flywaydb.core.api.callback입니다.플라이웨이 콜백 (0) | 2023.07.17 |
---|---|
사전 값을 여러 개 가져오는 방법? (0) | 2023.07.17 |
Spring Boot 애플리케이션 구성에서 Spring Cloud {cipher}를 사용하는 방법이 있습니까? (0) | 2023.07.17 |
타임스탬프에서 T와 Z는 정확히 무엇을 의미합니까? (0) | 2023.07.17 |
[Vue warn]:렌더 오류: "TypeError: 정의되지 않은 'products' 속성을 읽을 수 없습니다." (0) | 2023.07.17 |