我是在一个 BarButtonItem 上做的,我需要 2 个标签,一个接一个,具有不同的文本大小和属性。
我设置了对 2 UILabel 的强引用,然后:
-(void) initBottomBar
{
UIColor *labelColor;
if ([Utility getiOSVersion] == 7)
labelColor = [UIColor colorWithRed:43.0f/255.0f green:41.0f/255.0f blue:81.0f/255.0f alpha:1.0f]; // grayblue color
else
labelColor = [UIColor whiteColor];
labelStringCategory = [[UILabel alloc] initWithFrame:CGRectMake(0, 3, 300, 22)];
labelStringCategory.backgroundColor = [UIColor clearColor];
labelStringCategory.textColor = labelColor;
labelStringCategory.font = [UIFont systemFontOfSize:14];
labelStringCategory.numberOfLines = 1;
labelStringCategory.textAlignment = NSTextAlignmentLeft;
labelStringCategory.adjustsFontSizeToFitWidth = YES;
labelStringCategory.text = @"First Row";
changeStringCategory = [[UILabel alloc] initWithFrame:CGRectMake(0, 19, 300, 22)];
changeStringCategory.backgroundColor = [UIColor clearColor];
changeStringCategory.textColor = labelColor;
changeStringCategory.font = [UIFont systemFontOfSize:12];
changeStringCategory.numberOfLines = 1;
changeStringCategory.textAlignment = NSTextAlignmentLeft;
changeStringCategory.adjustsFontSizeToFitWidth = YES;
changeStringCategory.text = @"Second row";
UIButton *displayButton = [UIButton buttonWithType:UIButtonTypeCustom];
displayButton.frame = CGRectMake(0, 0, 300, 44);
[displayButton addSubview:labelStringCategory];
[displayButton addSubview:changeStringCategory];
displayButton.showsTouchWhenHighlighted = YES;
[displayButton addTarget:self action:@selector(displayCategorySelected:) forControlEvents:UIControlEventTouchDown];
UIBarButtonItem *labelStringCategoryBarItem = [[UIBarButtonItem alloc] initWithCustomView:displayButton];
//...
然后我可以在两个标签上分别设置 text 或 textattribute 。例如,要将 1 个标签的部分子字符串设置为粗体:
const CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
//UIColor *foregroundColor = [UIColor whiteColor];
// Create the attributes
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
regularFont, NSFontAttributeName, nil];
NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
boldFont, NSFontAttributeName, nil];
const NSRange range = NSMakeRange(iFrom,iTo - iFrom);
// Create the attributed string (text + attributes)
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:aText
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
// Set it in our UILabel and we are done!
[aLabel setAttributedText:attributedText];
希望这可以帮助!米克