Search code examples
ios7uibuttonnsattributedstring

UIButton with multi-line titleLabel with NSAttributedString doesn't work in iOS 7 but works in iOS8


In my project i have a requirement to show a UIButton that has two lines of text in its titleLabel With NSAttributedString. Its working fine in iOS8 but Where as in iOS7 its not working,i can see two lined text after selected button.

This is the code I'm using:

calendarBtn= [UIButton buttonWithType:UIButtonTypeCustom];
calendarBtn.frame=CGRectMake(50 ,10, 45, 45);
[calendarBtn addTarget:self action:@selector(calendarBtnclicked:)forControlEvents:UIControlEventTouchUpInside];
calendarBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
calendarBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
calendarBtn.titleLabel.numberOfLines=2;
[calendarBtn setTitleColor:BLACK_COLOR forState:UIControlStateNormal];


NSString *dateString=@"27\nApr";
dateString=[dateString uppercaseString];
[calendarBtn setTitle:dateString forState:UIControlStateNormal];


// Font For 27
UIFont *ddFont = [UIFont fontWithName:ArkitechLight size:17.0f];

NSMutableDictionary *ddDict = [NSMutableDictionary dictionaryWithObject:ddFont forKey:NSFontAttributeName];
NSMutableParagraphStyle *style  = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:3];
style.alignment=NSTextAlignmentCenter;
[style setLineBreakMode:NSLineBreakByWordWrapping];
[ddDict addEntriesFromDictionary:@{NSParagraphStyleAttributeName : style,}];

NSMutableAttributedString *ddStr = [[NSMutableAttributedString alloc] initWithString:[dateString substringToIndex:2] attributes:ddDict];

// Font For Apr
UIFont *mmmFont = [UIFont fontWithName:ArkitechLight size:11.5f];
NSDictionary *mmmDict = [NSDictionary dictionaryWithObject:mmmFont forKey:NSFontAttributeName];
NSMutableAttributedString *mmmString = [[NSMutableAttributedString alloc]initWithString:[dateString substringFromIndex:2] attributes:mmmDict];
[ddStr appendAttributedString:mmmString];

calendarBtn.titleLabel.attributedText=ddStr;

Solution

  • You need to use this line to set attributed title

    [calendarBtn setAttributedTitle: ddStr forState:UIControlStateNormal];
    

    instead of

    calendarBtn.titleLabel.attributedText=ddStr;
    

    Hope it helps :)