2012-10-09 16 views
6

Sto cercando un modo per cambiare il colore in UIRefreshControl. Il testo viene mostrato in un NSAttributedString, così cerco di usare CoreText.framework:Cambia colore in attributoTitle in 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; 

Il testo viene visualizzato correttamente, ma il colore è sempre il grigio di default. Qualche idea?

risposta

11

Si dovrebbe usare NSForegroundColorAttributeName, non kCTForegroundColorAttributeName.


Inoltre, l'intervallo passato deve essere NSMakeRange(0, [s length]);.

+0

Ancora non funziona ... – Fry

+1

@Fry oh r ight, l'intervallo è anche sbagliato. Risposta modificata –

5

Il parametro "valore" che si sta passando al metodo "addAttribute" è un CGColor, utilizzare invece UIColor e funzionerà! [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; 

ho trovato la risposta qui: http://ioscreator.com/format-text-in-ios6-attributed-strings/

1

utilizzare questo metodo,

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

quindi,

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

Versione semplice:

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

In Swift è possibile impostare il colore del attributedTitle come segue:

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)])