2014-09-13 13 views
8

Ich möchte den Titel eines UIButton, der einen zugeordneten Titel hat, programmgesteuert ändern. Die Schaltfläche wird in IB erstellt. Ich möchte die Attribute nicht nur den Titel/Text ändern.Programmierten Titel von UIButton programmgesteuert ändern

Ich habe den folgenden Code ausprobiert, kann aber keinen Weg finden, den Titel des NSAttributedString zu ändern.

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

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

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

Vielen Dank!

Antwort

15

Teilweise haben Sie die Antwort.

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

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

[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

Statt der Schaffung NSAttributedString erstellen NSMutableAttributedString dann können Sie nur die Zeichenfolge wie folgt festgelegt.

2

Es hängt wirklich von Ihrem attributedString:

  • ‚Ebene‘ attributedString: Das bedeutet, Ihr attrString nur 1 Satz von Attributen hat, die auf die gesamte Länge des Strings gelten. In diesem Fall können Sie wie folgt vorgehen:

    NSAttributedString *attrString = WHATEVER; 
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL]; 
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER 
                        attributes:attributes]; 
    
  • Ihr attributedString hat verschiedene Bereiche von Attributen:
    Dies kann wirklich auf die Struktur kompliziert werden, abhängig von Ihnen attributedString, weil Sie eine Menge Bereich würden zu tun haben, Handhabung usw. In diesem Fall sollten Sie einen neuen NSMutableAttributedString erstellen und die Attribute von Grund auf neu setzen.

4

Swift 3 Antwort:

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