如何仅突出显示UILabel – IOS中的文本

我只想突出显示UILabel文本,我曾试着给backgroundColor作标签,但突出显示空格也看起来不太好。 所以有没有什么办法来突出显示文本,而不用调整UILabel大小。

请检查图像,这里的标签比文字大(中心alignment)

在这里输入图像说明

感谢名单。

大多数其他的解决scheme不考虑跨越多行的文本,而只是突出显示文本,他们都非常hacky涉及额外的子视图。

iOS 6及更高版本的解决scheme是使用属性string:

 NSMutableAttributedString *s = [[NSMutableAttributedString alloc] initWithString:yourString]; [s addAttribute:NSBackgroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, s.length)]; label.attributedText = s; 

这将在文本后面添加一个子视图,大小正确:

 CGSize size= [[label text] sizeWithFont:[UIFont systemFontOfSize:18.0]]; NSLog(@"%.1f | %.1f", size.width, size.height); NSLog(@"%.1f | %.1f", label.frame.size.width, label.frame.size.height); UIView *highlightView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)]; [highlightView setBackgroundColor:[UIColor greenColor]]; [self.view insertSubview:highlightView belowSubview:label]; [highlightView setCenter:label.center]; 

别忘了: [label setBackgroundColor:[UIColor clearColor]];

尝试这个

MTLabel

  MTLabel *label4 = [MTLabel labelWithFrame:CGRectMake(20, 270, 250, 60) andText:@"This label is highlighted, has a custom line height, and adjusts font size to fit inside the label."]; [label4 setLineHeight:22]; [label4 setFont:[UIFont fontWithName:@"Helvetica" size:30]]; [label4 setAdjustSizeToFit:YES]; [label4 setMinimumFontSize:15]; [label4 setFontHighlightColor:[[UIColor orangeColor] colorWithAlphaComponent:0.5]]; [self.view addSubview:label4]; 

你可以有一个UIImageView ,设置你的select的背景颜色,然后放置你的UIlabel 。 这一定会解决你的问题。 以下是解决方法代码:

  UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 100, 40)]; [imgView setBackgroundColor:[UIColor brownColor]]; [self.view addSubview:imgView]; UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)]; [label setBackgroundColor:[UIColor clearColor]]; [label setTextAlignment:UITextAlignmentCenter]; label.text = @"My Label"; [imgView addSubview:label]; [label release]; [imgView release]; 

您也可以使用Interface Builder实现相同的function