Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton textLabel with different fonts

Tags:

ios

uibutton

Is there a way to have a UIButton with two different font sizes in its textLabel? Natively?

I don't want to have a UILabel on top.

like image 253
George Asda Avatar asked Dec 01 '22 16:12

George Asda


2 Answers

You can do this in interface builder. This GIF will show you how to increase the size of one section of the text and perhaps change its font.

enter image description here

To do this in code:

NSString *fullString = @"This bit's plain. This bit's bigger";
NSRange rangeOfPlainBit = [fullString rangeOfString:@"This bit's plain."];
NSRange rangeOfBigBit = [fullString rangeOfString:@"This bit's bigger"];

NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:fullString];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"My-font" size:15.0],
                                NSForegroundColorAttributeName: [UIColor whiteColor]}
                        range:rangeOfPlainBit];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"My-font" size:25.0],
                                NSForegroundColorAttributeName: [UIColor whiteColor]}
                        range:rangeOfBigBit];

[self.myButton setAttributedTitle:attributedText forState:UIControlStateNormal];
like image 142
Gordonium Avatar answered Dec 10 '22 13:12

Gordonium


SWIFT 3

 func customizeButtonFont(fullText: String, mainText: String, creditsText: String, button: UIButton) {
        let fontBig = UIFont(name:"SFUIDisplay-Medium", size: 16.0)
        let fontSmall = UIFont(name:"SFUIDisplay-Light", size: 14.0)
        let attributedString = NSMutableAttributedString(string: fullText, attributes: nil)

        let bigRange = (attributedString.string as NSString).range(of: mainText)
        let creditsRange = (attributedString.string as NSString).range(of: creditsText)
        attributedString.setAttributes([NSAttributedStringKey.font: fontBig, NSAttributedStringKey.foregroundColor: UIColor.white], range: bigRange)
        attributedString.setAttributes([NSAttributedStringKey.font: fontSmall, NSAttributedStringKey.foregroundColor: UIColor.white], range: creditsRange)

        button.setAttributedTitle(attributedString, for: .normal)
    }
like image 30
Svitlana Avatar answered Dec 10 '22 12:12

Svitlana