如何为UIView底部左右两角制作类似老式键盘空格键的弧形?
实现底部左右圆角的UIView(仿老式键盘空格键)
嘿,这个需求我之前做类似自定义控件时刚好碰到过!要做出老式键盘空格键那种仅底部左右两个角落带弧形的UIView,这里有两种实用的实现方案,你可以根据自己的iOS版本需求来选:
方案一:自定义路径+CAShapeLayer(适配全iOS版本)
这种方法通过手动绘制贝塞尔路径,再用路径生成的CAShapeLayer作为View的遮罩,完全自定义圆角位置和弧度,兼容性拉满。
Swift代码示例:
import UIKit class BottomRoundedView: UIView { // 可自定义圆角半径,按需调整 var cornerRadius: CGFloat = 8.0 { didSet { updateMask() } } override func layoutSubviews() { super.layoutSubviews() updateMask() } private func updateMask() { let shapeLayer = CAShapeLayer() // 精准绘制仅底部左右圆角的路径 let path = UIBezierPath( roundedRect: bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius) ) shapeLayer.path = path.cgPath layer.mask = shapeLayer } }
Objective-C代码示例:
#import <UIKit/UIKit.h> @interface BottomRoundedView : UIView @property (nonatomic, assign) CGFloat cornerRadius; @end @implementation BottomRoundedView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _cornerRadius = 8.0; } return self; } - (void)layoutSubviews { [super layoutSubviews]; [self updateMask]; } - (void)updateMask { CAShapeLayer *shapeLayer = [CAShapeLayer layer]; UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(self.cornerRadius, self.cornerRadius)]; shapeLayer.path = path.CGPath; self.layer.mask = shapeLayer; } - (void)setCornerRadius:(CGFloat)cornerRadius { _cornerRadius = cornerRadius; [self updateMask]; } @end
方案二:利用系统API(iOS 11+)
如果你只需要适配iOS 11及以上版本,直接用系统提供的maskedCorners属性就可以了,代码更简洁,不需要自定义图层:
Swift代码示例:
let customView = UIView(frame: CGRect(x: 50, y: 100, width: 300, height: 60)) customView.backgroundColor = .gray // 设置圆角半径 customView.layer.cornerRadius = 8.0 // 指定仅底部左右两个角应用圆角 customView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] // 若需裁剪子视图,记得打开masksToBounds customView.layer.masksToBounds = true
Objective-C代码示例:
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(50, 100, 300, 60)]; customView.backgroundColor = [UIColor grayColor]; customView.layer.cornerRadius = 8.0; customView.layer.maskedCorners = kCALayerMinXMaxYCorner | kCALayerMaxXMaxYCorner; customView.layer.masksToBounds = YES;
小提示
- 如果View需要动态改变尺寸(比如AutoLayout适配不同屏幕),方案一中的
layoutSubviews会自动更新遮罩;方案二基于系统API,也会自动适配尺寸变化。 - 调整
cornerRadius的值就能控制弧形弧度,完全匹配老式键盘空格键的样式。
内容的提问来源于stack exchange,提问作者roshan.k
相关产品推荐
相关产品推荐

