Change color to title attribute in UIRefreshControl

I am looking for a way to change color in a UIRefreshControl . The text is displayed in NSAttributedString , so I'm trying to use 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; 

The text is displayed correctly, but the color is always gray by default. Any ideas?

+6
source share
6 answers

You should use NSForegroundColorAttributeName , not kCTForegroundColorAttributeName .


In addition, the transmitted range must be NSMakeRange(0, [s length]); .

+11
source

Simple version:

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

In Swift, you can set the color of the title attribute as follows:

 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)]) 
+8
source

The value parameter that you pass to the addAttribute method is CGColor, use UIColor instead, and it will work! [UIColor redColor] .CGColor

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

I found the answer here: http://ioscreator.com/format-text-in-ios6-attributed-strings/

+2
source

use this method

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

Consequently,

 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]; 
+1
source

Source: https://habr.com/ru/post/927252/


All Articles