2012-10-09 46 views
6

Tôi đang tìm cách thay đổi màu trong UIRefreshControl. Các văn bản được hiển thị trong một NSAttributedString, vì vậy tôi cố gắng sử dụng CoreText.framework:Thay đổi màu thành thuộc tínhTitle trong UIRefreshControl

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

Các văn bản được hiển thị một cách chính xác, nhưng màu sắc luôn là màu xám mặc định. Bất kỳ ý tưởng nào?

Trả lời

11

Bạn nên sử dụng NSForegroundColorAttributeName, không phải kCTForegroundColorAttributeName.


Ngoài ra, phạm vi được truyền phải là NSMakeRange(0, [s length]);.

+0

Vẫn không hoạt động ... – Fry

+1

@Fry oh r ight, phạm vi cũng sai. Câu trả lời đã chỉnh sửa. –

5

Thông số "giá trị" bạn chuyển đến phương thức "addAttribute" là CGColor, sử dụng UIColor thay thế và nó sẽ hoạt động! [UIColor redColor] .CGColor

NSString *s = @"Hello"; 
NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s]; 
[a addAttribute:kCTForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(s)]; 
refreshControl.attributedTitle = a; 
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; 

Tôi tìm thấy câu trả lời ở đây: http://ioscreator.com/format-text-in-ios6-attributed-strings/

1

sử dụng phương pháp này,

  • (id) initWithString: (NSString *) thuộc tính str : (NSDictionary *) attrs;
  • (id) initWithAttributedString: (NSAttributedString *) attrStr;

do đó,

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]; 
8

phiên bản đơn giản:

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

Trong Swift bạn có thể thiết lập màu sắc của attributedTitle như sau:

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)]) 
Các vấn đề liên quan