How to remove border from some part of UIView?

2019-05-02 16:08发布

问题:

I am having a UIView which contains other subviews. I am applying border to this UIView and the border is applied to the whole UIView. For that see the first image.

But do not want the border around the title where it says "Leaderboard". How can i remove the border for that portion only. See the below image and in that see that there is no border around the header Leaderboard..

回答1:

NO,CALayer borders don’t support that behavior.

But you can try an alternate method if you need to implement this, try adding an n-point-wide opaque subview with your desired border color as its background color, on each side of your main view.

Add this Code:

CGSize mainViewSize = theView.bounds.size;
CGFloat borderWidth = 2;
UIColor *borderColor = [UIColor redColor];
CGFloat heightfromTop = 25;
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, heightfromTop borderWidth, mainViewSize.height-heightfromTop)];
UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(mainViewSize.width - borderWidth, heightfromTop, borderWidth, mainViewSize.height-heightfromTop)];
leftView.opaque = YES;
rightView.opaque = YES;
leftView.backgroundColor = borderColor;
rightView.backgroundColor = borderColor;

[mainView addSubview:leftView];
[mainView addSubview:rightView];

This will add borders to both sides only.Repeat the same idea for top and bottom also.

NB : heightfromTop is the height of the top section where you don't want the border view to be present, you can alter it as per your needs



回答2:

You can subclass the UIView and implement the drawRect like:

- (void)drawRect:(CGRect)rect
{       
      float borderSize = 3.0f;

     //draw the bottom border
     CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
     CGContextFillRect(context, CGRectMake(0.0f, self.frame.size.height - borderSize, self.frame.size.width, borderSize));

     //draw the right border
    CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextFillRect(context, CGRectMake(0.0f,0.0f, borderSize,self.frame.size.height));

     //draw the left border 
    CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextFillRect(context, CGRectMake(self.frame.size.width - borderSize,0.0f, borderSize,self.frame.size.height));
}

Now, you need to use the subclassed UIView for creating the needed view.