在带有圆角的 UIButton 中添加底部边框
Posted
技术标签:
【中文标题】在带有圆角的 UIButton 中添加底部边框【英文标题】:Add a bottom border in a UIButton with rounded corners 【发布时间】:2014-05-23 10:04:05 【问题描述】:如何在带有圆角的 UIButton 中添加左右边框?
这是我的按钮,我也想要边框的圆角:
还有我的按钮的源代码:
- (void)initialise;
//add border
[self addBottomBorderWithColor:[UIColor grayColor] andWidth:2];
[self addRightBorderWithColor:[UIColor grayColor] andWidth:2];
//round
self.layer.cornerRadius = 8.0f;
- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(self.frame.size.width, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
【问题讨论】:
【参考方案1】:您可以添加一个比您的按钮稍大的 CALayer 并用负边距偏移它,以便隐藏顶部和左侧边框。请注意,我现在无法对其进行测试,它可能需要进一步调整,但它应该会给你一个大致的想法:
-(void)initialise;
//add border
[self addBorderWithColor:[UIColor grayColor] andWidth:2];
//round
self.layer.cornerRadius = 8.0f;
- (void)addBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth
CALayer *border = [CALayer layer];
border.borderColor = color.CGColor;
border.frame = CGRectMake(-borderWidth, -borderWidth, self.frame.size.width+borderWidth, self.frame.size.height+borderWidth);
border.borderWidth = borderWidth;
border.cornerRadius = 8.f;
[self.layer addSublayer:border];
self.layer.masksToBounds = YES;
【讨论】:
自动布局怎么样?在旋转设备的情况下,您需要更改 CALayer 框架。以上是关于在带有圆角的 UIButton 中添加底部边框的主要内容,如果未能解决你的问题,请参考以下文章