Search code examples
objective-cuilabeldrawrectnsattributedstringcore-text

Draw line in UILabel before and after text


I want to draw a line before and after a string in UILabel exactly like the following image:

PS: the text is not static, so i can't tell what is the exact text width, otherwise i would put two static lines before and after the text.

PS: Also i can't put the label above a line and give the label background color same to the view background because i have gradient color in the lower view.

UILabel with line around text


Solution

  • I Hope below is what you was looking for...

    #import "ViewController.h"
    
    @interface ViewController () {
        UILabel *textLabel;
        UILabel *fakeTextLabel;
        UILabel *lineLabel1;
        UILabel *lineLabel2;
    }
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        self.view.backgroundColor = [UIColor lightGrayColor];
        NSString *labelText = @"  MOBILE INTERNET  ";
        fakeTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
        fakeTextLabel.backgroundColor = [UIColor blackColor];
        fakeTextLabel.textColor = [UIColor whiteColor];
        fakeTextLabel.text = labelText;
        [fakeTextLabel sizeToFit]; // this is very important...
        fakeTextLabel.hidden = YES;
        [self.view addSubview:fakeTextLabel];
    
        int lineWidth = (320-fakeTextLabel.frame.size.width);
        lineWidth = lineWidth / 2.00;
        textLabel = [[UILabel alloc] initWithFrame:CGRectMake(320-lineWidth-fakeTextLabel.frame.size.width, 200, fakeTextLabel.frame.size.width, 100)];
        textLabel.text = labelText;
        textLabel.textColor = [UIColor greenColor];
        [self.view addSubview:textLabel];
    
    
        lineLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 249, lineWidth, 2)];
        lineLabel1.text = @"";
        lineLabel1.backgroundColor = [UIColor redColor];
    
        lineLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(lineWidth+fakeTextLabel.frame.size.width, 249, lineWidth, 2)];
        lineLabel2.text = @"";
        lineLabel2.backgroundColor = [UIColor redColor];
    
        [self.view addSubview:lineLabel1];
        [self.view addSubview:lineLabel2];
    }