Ios 是否使用NSAttributedString更改字符串颜色?
我有一个用于调查的滑块,根据滑块的值显示以下字符串:“非常糟糕,糟糕,好,好,非常好” 以下是滑块的代码:Ios 是否使用NSAttributedString更改字符串颜色?,ios,cocoa-touch,nsattributedstring,Ios,Cocoa Touch,Nsattributedstring,我有一个用于调查的滑块,根据滑块的值显示以下字符串:“非常糟糕,糟糕,好,好,非常好” 以下是滑块的代码: - (IBAction) sliderValueChanged:(UISlider *)sender { scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]]; NSArray *texts=[NSArray arrayWithObjects:@"Very Bad", @"Bad", @"O
- (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];
}
我希望“非常坏”是红色,“坏”是橙色,“好”是黄色,“好”和“非常好”是绿色
我不明白如何使用NSAttributedString
来完成这项工作 使用类似的方法(未选中编译器)
无需使用
NSAttributedString
。您所需要的只是一个带有适当textColor
的简单标签。此外,这个简单的解决方案将适用于所有版本的iOS,而不仅仅是iOS 6
但是,如果您不必要地希望使用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;
在Swift 4中:
// 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
var attributes = [NSAttributedStringKey: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
对于Swift 4:
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
var attributes = [NSAttributedStringKey: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
对于Swift 3:
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
var attributes = [NSAttributedStringKey: AnyObject]()
attributes[.foregroundColor] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
var attributes = [String: AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.red
let attributedString = NSAttributedString(string: "Very Bad", attributes: attributes)
label.attributedText = attributedString
对于Swift 4,
NSAttributedStringKey
具有一个名为foregroundColor
的静态属性foregroundColor
具有以下声明:
static let foregroundColor: NSAttributedStringKey
此属性的值是UIColor
对象。使用此属性可以指定渲染期间文本的颜色。如果未指定此属性,文本将以黑色呈现
下面的代码显示了如何使用foregroundColor
设置nsattributetedstring
实例的文本颜色:
import UIKit
let string = "Some text"
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red]
let attributedString = NSAttributedString(string: string, attributes: attributes)
下面的代码显示了一个可能的
UIViewController
实现,该实现依赖NSAttributedString
,以便从UISlider
更新UILabel
的文本和文本颜色:
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
}
但是请注意,对于此类示例,您实际上不需要使用NSAttributedString
,只需依赖UILabel
的text
和textColor
属性即可。因此,您可以用以下代码替换updateDisplay()
实现:
func updateDisplay() {
label.text = currentStatus.display.text
label.textColor = currentStatus.display.color
slider.value = Float(currentStatus.rawValue)
}
您可以创建
或应用具有范围的自定义属性
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)];
可用属性:
更新: Swift 5.1 Swift 4.2的更新
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = UIColor.blue
let attributedString = NSAttributedString(string: "Very Bad",
attributes: attributes)
label.attributedText = attributedString
Swift班轮一艘:
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;
}
..你是说滑翔机?那没有标签。所以基本上是关于一个带有字体颜色的UILabel?或者你想把文本的一部分涂上颜色?使用这个库可能会有重复,这很简单。嘿,阿努普,很高兴再次见到你!我修改了您提供的代码,用self.scanLabel.text替换了self.text.text,但在“word”处出现错误。我试着用“非常糟糕”来代替它,但没有运气。我从这里复制了我的答案,谢谢你,但我运气不好-[\uu NSCFString\u ui\u synthesizeAttributedSubstringFromRange:usingDefaultAttributes:]:发送到实例0x1f845af0 2013-01-11 16:27:34.939 yellaProto[7829:907]***由于未捕获异常“NSInvalidArgumentException”,终止应用程序,原因:'-[\uu NSCFString\u ui\u synthesizeAttributedSubstringFromRange:usingDefaultAttributes:]:未识别的选择器发送到实例0x1f845af0'只需尝试找出otu什么“文本”@Morkrom:如果您在这个答案中看到第二条注释,您就会知道:pI不理解所有的否决票。我的答案比使用属性字符串简单得多。OP无需为此任务使用
NSAttributedString
。如果标签的文本需要多个属性,但它不需要,这是一回事。整个标签一次只能有一种颜色。@rubeénE.Marín但这就是问题所在。OP错误地认为解决方案需要使用nsattributestring
。这就是他们的要求。真正的问题应该是“如何根据标签的值设置标签的颜色”。我指出该解决方案不需要NSAttributedString
,并给出了一个简单得多的答案。OP同意接受我更简单的答案。如果OP真的想要NSAttributedString
,他们不会接受我的答案。所以没有理由投反对票。我回答了真实的问题,OP接受了。在这种情况下,我会用NSAttributedString解决这个问题,然后,我会指出您针对OP这一特殊情况的更简单、更有效的解决方案。人们可能会对您的解决方案感到失望,因为他们正在寻找改变NSAttributedString上文本颜色的方法(这可以解释您的反对票).Rubén是对的:我来这里是因为我确实需要在属性字符串中设置颜色,因为我正在构建一个具有多种颜色和字体大小的复合属性字符串。我需要的关键信息是NSForegroundColorAttributeName
键,我在Apple文档中很难找到它。谢谢你仍然回答这个问题!!即使OP实际上并不需要它。很多时候,我在谷歌上搜索某个东西,最后发现一个堆栈溢出问题,这正是我要找的,结果发现回答这个问题的聪明人认为OP实际上不需要问题标题所要求的,并回答了一个完全不同的问题。好吧,未来来自搜索结果的人,其中可能有1000个搜索结果,而不是1个搜索结果,他们可能真的想要一个解决文章标题中所问问题的方法。