带有 NSAttributedString 的多行 titleLabel 的 UIButton 在 iOS 7 中不起作用,但在 iOS8 中起作用

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

在我的项目中,我需要显示一个 UIButton,它的 titleLabel 中有两行文本和 NSAttributedString。它在 iOS8 中工作正常,但在 iOS7 中它不起作用,我可以在选定按钮后看到两行文本。

这是我正在使用的代码:

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;

您需要使用此行来设置属性标题

[calendarBtn setAttributedTitle: ddStr forState:UIControlStateNormal];

而不是

calendarBtn.titleLabel.attributedText=ddStr;

希望对您有所帮助:)