2014-09-13 31 views
8

Chcę programowo zmienić tytuł UIButton, który ma przypisany tytuł. Przycisk jest tworzony w IB. Nie chcę zmieniać atrybutów tylko tytuł/tekst.Programowa zmiana przypisanego tytułu UIButton

Próbowałem kodu poniżej, ale nie mogę znaleźć sposób, aby zmienić tytuł NSAttributedString.

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

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

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

Dziękujemy!

Odpowiedz

15

Częściowo masz odpowiedź.

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

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

[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

Zamiast tworzyć NSAttributedString tworzyć NSMutableAttributedString następnie można po prostu ustawić ciąg takiego.

2

To naprawdę zależy od attributedString:

  • „zwykły” attributedString: Oznacza to attrString ma tylko 1 zestaw atrybutów, które mają zastosowanie do całej długości łańcucha. W tym przypadku, można wykonać następujące czynności:

    NSAttributedString *attrString = WHATEVER; 
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL]; 
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER 
                        attributes:attributes]; 
    
  • Twój attributedString ma różne zakresy atrybuty:
    To może się naprawdę skomplikowane zależności od struktury wy attributedString, bo trzeba by zrobić dużo zakresie obsługa itp. W tym przypadku lepiej jest utworzyć nowy NSMutableAttributedString i ustawić atrybuty od zera.

4

Swift 3 odpowiedź:

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) 
} 
Powiązane problemy