6

我正在寻找一种改变颜色的方法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;

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

4

7 回答 7

11

你应该使用NSForegroundColorAttributeName,而不是kCTForegroundColorAttributeName


此外,通过的范围应该是NSMakeRange(0, [s length]);.

于 2012-10-09T18:39:15.757 回答
11

在 Swift 中,您可以按如下方式设置属性标题的颜色:

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)])
于 2015-05-09T22:20:23.623 回答
8

简单版:

NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"Refresh…" 
attributes: @{NSForegroundColorAttributeName:[UIColor redColor]}];
refreshControl.attributedTitle = [[NSAttributedString alloc]initWithAttributedString:title];
于 2014-04-24T01:33:29.300 回答
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;
于 2012-12-04T04:54:17.840 回答
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/

于 2013-05-08T15:00:31.283 回答
2

斯威夫特版本 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
于 2018-07-05T09:37:41.513 回答
1

使用这种方法,

  • (id)initWithString:(NSString *)str 属性:(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];
于 2014-01-22T10:11:31.850 回答