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.
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.
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];
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With