2014-09-13 24 views
8

Desidero modificare a livello di programmazione il titolo di uno UIButton che ha un titolo attribuito. Il pulsante viene creato in IB. Non voglio cambiare gli attributi solo il titolo/testo.Modifica titolo attribuito di UIButton

Ho provato il codice riportato di seguito ma non riesco a trovare un modo per modificare il titolo dello NSAttributedString.

NSAttributedString *attributedString = [self.deleteButton attributedTitleForState:UIControlStateNormal]; 

// How can I change title of attributedString without changing the attributes? 

[self.deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

Grazie!

risposta

15

In parte si ha la risposta.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[_ deleteButton attributedTitleForState:UIControlStateNormal]]; 

[attributedString replaceCharactersInRange:NSMakeRange(0, attributedString.length) withString:@"Your new string"]; 

[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

Invece di creare NSAttributedString creare NSMutableAttributedString allora si può solo impostare la stringa in questo modo.

2

Dipende molto sul attributedString:

  • 'plain' attributedString: Questo significa che il tuo attrString ha solo 1 set di attributi che si applicano a tutta la lunghezza della stringa. In questo caso, è possibile effettuare le seguenti operazioni:

    NSAttributedString *attrString = WHATEVER; 
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL]; 
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER 
                        attributes:attributes]; 
    
  • tua attributedString ha diverse gamme di attributi:
    questo può diventare davvero complicato a seconda della struttura di voi attributedString, perché si sarebbe dovuto fare un sacco di gamma gestione, ecc. In questo caso, è meglio creare un nuovo NSMutableAttributedString e impostare gli attributi da zero.

4

Swift 3 risposta:

if let attributedTitle = yourButton.attributedTitle(for: .normal) { 
    let mutableAttributedTitle = NSMutableAttributedString(attributedString: attributedTitle) 
    mutableAttributedTitle.replaceCharacters(in: NSMakeRange(0, mutableAttributedTitle.length), with: "New title") 
    yourButton.setAttributedTitle(mutableAttributedTitle, for: .normal) 
} 
Problemi correlati