在UIRefreshControl中将颜色更改为attributionTitle

时间:2012-10-09 12:37:40

标签: ios ios6 nsattributedstring uirefreshcontrol

我正在寻找一种在UIRefreshControl中改变颜色的方法。 该文字显示在NSAttributedString中,因此我尝试使用CoreText.framework

 NSString *s = @"Hello";
 NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s];
 [a addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSRangeFromString(s)];
 refreshControl.attributedTitle = a;

文本显示正确,但颜色始终为默认灰色。 有什么想法吗?

7 个答案:

答案 0 :(得分:11)

您应该使用NSForegroundColorAttributeName,而不是kCTForegroundColorAttributeName


此外,传递的范围应为NSMakeRange(0, [s length]);

答案 1 :(得分:9)

在Swift中,您可以按如下方式设置 attributionTitle 的颜色:

self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: [NSForegroundColorAttributeName: UIColor(red: 255.0/255.0, green: 182.0/255.0, blue: 8.0/255.0, alpha: 1.0)])

答案 2 :(得分:8)

简单版本:

NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"Refresh…" 
attributes: @{NSForegroundColorAttributeName:[UIColor redColor]}];
refreshControl.attributedTitle = [[NSAttributedString alloc]initWithAttributedString:title];

答案 3 :(得分:5)

您传递给“addAttribute”方法的“value”参数是CGColor,而是使用UIColor,它将起作用! [UIColor redColor] .CGColor

NSString *s = @"Hello";  
NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s];  
[a addAttribute:kCTForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(s)]; 
refreshControl.attributedTitle = a;

答案 4 :(得分:2)

NSString *s = @"Hello";

NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s];

NSDictionary *refreshAttributes = @{
  NSForegroundColorAttributeName: [UIColor blueColor],
};

[a setAttributes:refreshAttributes range:NSMakeRange(0, a.length)];

refreshControl.attributedTitle = a;

我在这里找到答案:http://ioscreator.com/format-text-in-ios6-attributed-strings/

答案 5 :(得分:1)

使用此方法,

  • (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
  • (id)initWithAttributedString:(NSAttributedString *)attrStr;

因此,

NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setObject:[UIColor whiteColor] forKey:NSBackgroundColorAttributeName]; //background color :optional
[attributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];  //title text color :optionala
NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"Refresh!!" attributes:attributes];

_refreshcontrol.attributedTitle = [[NSAttributedString alloc]initWithAttributedString:title];

答案 6 :(得分:1)

Swift版本4(iOS 11)

        let myString = "Pull to refresh"
        let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.black ]
        let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
        refreshControl.attributedTitle = myAttrString