Reputation: 777
I want to programmatically change the title of an UIButton
which has an attributed title.
The button is created in IB. I do not want to change the attributes just the title/text.
I've tried the code below but cannot find a way to change the title of the NSAttributedString
.
NSAttributedString *attributedString = [self.deleteButton attributedTitleForState:UIControlStateNormal];
// How can I change title of attributedString without changing the attributes?
[self.deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal];
Thank you!
Upvotes: 16
Views: 19474
Reputation: 4079
Swift 3 answer:
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)
}
Upvotes: 22
Reputation: 3261
It really depends on your attributedString:
'plain' attributedString: This means your attrString has only 1 set of attributes which apply to the entire length of the string. In this case, you can do the following:
NSAttributedString *attrString = WHATEVER;
NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL];
NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER
attributes:attributes];
your attributedString has different ranges of attributes:
This can get really complicated depending on the structure of you attributedString, because you would have to do a lot of range handling, etc. In this case, you are better off creating a new NSMutableAttributedString
and set the attributes from scratch.
Upvotes: 3
Reputation: 10739
Partially you have the answer.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[_ deleteButton attributedTitleForState:UIControlStateNormal]];
[attributedString replaceCharactersInRange:NSMakeRange(0, attributedString.length) withString:@"Your new string"];
[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal];
Instead of creating NSAttributedString
create NSMutableAttributedString
then you can just set the string like this.
Upvotes: 20