How to highlight only text in UILabel - IOS

后端 未结 4 1652
轻奢々
轻奢々 2020-12-14 22:57

I just want to highlight only text in UILabel, I have tried by giving backgroundColor for label, but it is highlighting the empty spaces also looks

4条回答
  •  被撕碎了的回忆
    2020-12-14 23:43

    This will add a subview behind the text, with the correct size:

    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];
    

    And don't forget: [label setBackgroundColor:[UIColor clearColor]];

提交回复
热议问题