Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw only top, right, and bottom border around a uilabel

Tags:

ios

uilabel

i try to add border for a uilabel, but i only want to have top, right, and bottom border.

like this

           ----------------
                          |
            I am a label  |
                          |
           ----------------

I try to use these codes, but it adds all 4 sides by default

    myLabel.layer.borderWidth = 1;
    myLabel.layer.borderColor = [UIColor blackColor];

Is that anyway i can only add 3 sides, or even 1 or 2 sides?

Thanks!

like image 368
user3276557 Avatar asked Feb 05 '14 18:02

user3276557


1 Answers

You can use a mask. This is the code I used to test the theory, and it works well:

// Define the border width in a variable, we'll be using it elsewhere
CGFloat borderWidth = 1.0;

// This creates a testing view to test the theory, in your case this will be your UILabel
UIView* view = [[UIView alloc] initWithFrame:CGRectMake(20, 60, 250, 100)];
view.layer.borderColor = [UIColor blackColor].CGColor;
view.layer.borderWidth = borderWidth;
[self.view addSubview:view];

// Create the mask to cover the area of the view you want to **show**
// Here, we create a mask that covers most of the view, except the left edge
// The mask needs to be coloured in black, as black acts as transparent, whereas white is opaque in mask parlance
UIView* mask = [[UIView alloc] initWithFrame:CGRectMake(borderWidth, 0, view.frame.size.width - borderWidth, view.frame.size.height)];
mask.backgroundColor = [UIColor blackColor];
view.layer.mask = mask.layer;

You can adjust the size and position of the mask (given the borderWidth) to show/hide the border edges you're interested in. The example above hides the left edge.

like image 164
WDUK Avatar answered Oct 25 '22 02:10

WDUK