OC/Swift 知识 UIButton
2026/7/21 20:19:01 网站建设 项目流程

一直觉得自己写的不是技术,而是情怀,一个个的教程是自己这一路走来的痕迹。靠专业技能的成功是最具可复制性的,希望我的这条路能让你们少走弯路,希望我能帮你们抹去知识的蒙尘,希望我能帮你们理清知识的脉络,希望未来技术之巅上有你们也有我。

属性

属性注释
frame约束
showsTouchWhenHighlighted点击数是闪光效果会被前景图片盖住中间部分
titleLabel.font设置文字大小
enabled隐藏按键
titleLabel.shadowOffset设置按键阴影
layer.cornerRadius设置按键圆角
layer.masksToBounds设置按键背景跟随圆角
adjustsImageWhenDisabled当按键禁用的情况下,图像的颜色会被画深一点,默认为YES;
adjustsImageWhenHighlighted当按键禁用情况下,图像的颜色会被画深一点,默认为YES
showsTouchWhenHighlighted点击时的闪光效果会被前景图片盖住中间部分
contentEdgeInsets设置按键内间距
contentHorizontalAlignment设置按钮内容的左对齐

方法

方法注释
- (void)setImage:(nullable UIImage *)image forState:(UIControlState)state设置按键的图片
- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state设置按键背景颜色
- (void)setTitle:(nullable NSString *)title forState:(UIControlState)state;设置文字文本
- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state设置文本颜色
- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents按键添加点击事件
- (void)setTitleShadowColor:(nullable UIColor *)color forState:(UIControlState)state设置按键阴影颜色

使用

//创建对象并设置frameself.btn=[[UIButton alloc]initWithFrame:CGRectMake(50,100,50,40)];[self.view addSubview:self.btn];//设置按键的图片[self.btn setImage:[UIImage imageNamed:@"msgS"]forState:UIControlStateNormal];//点击数是闪光效果会被前景图片盖住中间部分[self.btn setShowsTouchWhenHighlighted:YES];//设置按键背景颜色[self.btn setBackgroundImage:[UIImage imageNamed:@"msgS"]forState:UIControlStateNormal];//设置文字文本[self.btn setTitle:@"content"forState:UIControlStateNormal];//设置文字大小self.btn.titleLabel.font=[UIFont systemFontOfSize:22];//设置文字加粗self.btn.titleLabel.font=[UIFont boldSystemFontOfSize:22];//设置文本颜色[self.btn setTitleColor:[UIColor redColor]forState:UIControlStateNormal];//按键添加点击事件[self.btn addTarget:selfaction:@selector(btnClick)forControlEvents:UIControlEventTouchUpInside];//方法不带参数[self.btn addTarget:selfaction:@selector(btnClick:)forControlEvents:UIControlEventTouchUpInside];//方法带参数#selector(updateProgress(notification:))//Swift的写法button.addTarget(self,action:#selector(tapped(_:)),for:.touchUpInside)//Swift的写法//是否允许按键点击self.btn.enabled=NO;//设置按键阴影self.btn.titleLabel.shadowOffset=CGSizeMake(-5,-5);[self.btn setTitleShadowColor:[UIColor grayColor]forState:UIControlStateNormal];//设置按键圆角self.btn.layer.cornerRadius=5;//设置按键背景跟随圆角self.btn.layer.masksToBounds=YES;//当按键禁用的情况下,图像的颜色会被画深一点,默认为YES;self.btn.adjustsImageWhenDisabled=NO;//当按键禁用情况下,图像的颜色会被画深一点,默认为YESself.btn.adjustsImageWhenHighlighted=NO;//点击时的闪光效果会被前景图片盖住中间部分self.btn.showsTouchWhenHighlighted=NO;//设置按键内间距self.btn.contentEdgeInsets=UIEdgeInsetsMake(0,20,0,0);//设置按钮内容的左对齐self.btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;//方法带参数-(void)btnClick:(UIButton*)button{}

有时候需要我们继承UIControl自定义我们想要的按键,例如:上面图片,下面文字的按键系统自带的是没有的。
我自己也写过针对按键的封装。
https://blog.csdn.net/weixin_38716347/article/details/113832932

需求

0.关于阴影的使用

阴影的添加实际上就是在控件的后面中间有一个阴影图形的发散点,发散出来的效果,看起来就像阴影,所以设置阴影的半径大小在控件的基础上+2就可以了,透明度设置0.5适宜,颜色是黑色,偏移y轴 CGSizeMake(0, 1)+1,圆角半径可选不裁剪

shadowOffset: 阴影偏移

x 设置是数 阴影向
x 设置是数 阴影向
y 设置是数 阴影向
y 设置是数 阴影向

shadowOpacity: 阴影的透明度

0.0 - 1.0 之间


shadowColor:阴影背景

shadowRadius:阴影半径

cornerRadius:圆角半径

masksToBounds:不裁剪超出部分

方法1:(推荐)四周添加阴影

// 设置阴影的颜色 self.markerButton.layer.shadowColor = [UIColor blackColor].CGColor; // 设置阴影的偏移量,(x, y),负值可以让阴影向上或向左偏移 self.markerButton.layer.shadowOffset = CGSizeMake(0, 2); // 设置阴影的透明度 self.markerButton.layer.shadowOpacity = 0.5; // 设置阴影的模糊半径 self.markerButton.layer.shadowRadius = 5; // 设置圆角(可选) self.markerButton.layer.cornerRadius = 4; // 防止裁剪视图(如果有圆角),否则阴影可能会被裁剪 self.markerButton.layer.masksToBounds = NO;

方法2:四周添加阴影

UIView*views_1=[UIView new];[self.view addSubview:views_1];views_1.backgroundColor=[UIColor blackColor];views_1.frame=CGRectMake(50,350,100,100);// 阴影颜色views_1.layer.shadowColor=[UIColor blueColor].CGColor;// 阴影偏移量 默认为(0,3)UIBezierPath*path=[UIBezierPath bezierPathWithRect:CGRectMake(-4,-4,100+8,100+12)];// 阴影透明度views_1.layer.shadowOpacity=2;views_1.layer.shadowPath=path.CGPath;

1.是否允许按键点击

NO 不允许点击, YES 允许点击

//是否允许按键点击 self.btn.enabled = NO;

2.如何修改按键图片跟文字的间距

OC

推荐

[self.refreshButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 7.5, 0, 0)]; [self.refreshButton setImageEdgeInsets:UIEdgeInsetsMake(0, -7.5, 0, 0)];

修改前

修改后


直接上代码

// 设置图片和文本的内边距CGFloat spacing=8.0;// 图片和文本之间的间距self.trueButton.imageEdgeInsets=UIEdgeInsetsMake(0,-spacing/2,0,spacing/2);self.trueButton.titleEdgeInsets=UIEdgeInsetsMake(0,spacing/2,0,-spacing/2);self.trueButton.contentEdgeInsets=UIEdgeInsetsMake(0,spacing/2,0,spacing/2);// 可选,设置按钮内容的内边距// 调整按钮的大小以适应内容[self.trueButton sizeToFit];

Swift

iOS15以下

let spacing: CGFloat = 8 button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing/2, bottom: 0, right: spacing/2) button.titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing/2, bottom: 0, right: -spacing/2)

iOS15以上

var MOPuttonConfig = UIButton.Configuration.plain() MOPuttonConfig.imagePadding = 4 MOPuttonConfig.titlePadding = 0 MOPuttonConfig.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0) MOPuttonConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in var outgoing = incoming outgoing.font = UIFont.systemFont(ofSize: 14) outgoing.foregroundColor = Color.textTheme return outgoing } MOPuttonConfig.baseForegroundColor = Color.textTheme MOPuttonConfig.background.backgroundColor = .clear MOPButton.configuration = MOPuttonConfig

3.button文本显示居中对齐

self.memberButton.titleLabel.textAlignment=NSTextAlignmentCenter;self.memberButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;

Swift 右边对齐

button.contentHorizontalAlignment=.right button.contentEdgeInsets=UIEdgeInsets(top:0,left:0,bottom:0,right:1)

4.如何把button的文本内容全部显示出来

self.button=[UIButton buttonWithType:UIButtonTypeSystem];NSString*title=@"123456789qwertyuiopasdfghjklzxcvbnm";self.button.addTo(self.view).str(title).fnt(16).color([UIColor whiteColor]).bgColor([UIColor orangeColor]).makeCons(^{make.center.equal.view(self.view);make.width.equal.constants(200);make.height.equal.constants(100);});self.button.titleLabel.adjustsFontSizeToFitWidth=YES;[self.button sizeToFit];

5.按键的文本内容如何换行显示


self.button=[UIButton buttonWithType:UIButtonTypeSystem];[self.button setTitle:@"This is a long button title that needs to wrap to the next line"forState:UIControlStateNormal];[self.button.titleLabel setFont:[UIFont systemFontOfSize:17.0]];[self.button.titleLabel setNumberOfLines:0];// 设置为0表示自动换行[self.button.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];[self.button sizeToFit];self.button.addTo(self.view).color([UIColor whiteColor]).bgColor([UIColor orangeColor]).makeCons(^{make.center.equal.view(self.view);make.width.equal.constants(200);make.height.equal.constants(100);});self.button.titleLabel.adjustsFontSizeToFitWidth=YES;[self.button sizeToFit];

6.自定义按键(左字右图)

#import "SwitchServerButton.h" @interface SwitchServerButton() @property (nonatomic, strong) UILabel *titleLabel; @property (nonatomic, strong) UIImageView *imageView; @end @implementation SwitchServerButton - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; [self buildUI]; return self; } -(void) buildUI{ self.backgroundColor = [UIColor whiteColor]; self.titleLabel = [UILabel new]; self.titleLabel.textColor = [Color theme]; self.titleLabel.addTo(self).fnt(16).str(@"切换服务器").makeCons(^{ make.centerY.equal.view(self); make.left.equal.view(self).constants(5); }); self.imageView = [UIImageView new]; self.imageView.addTo(self).img(@"switch_server").makeCons(^{ make.width.height.equal.constants(25); make.centerY.equal.view(self); make.left.equal.view(self.titleLabel).right.constants(5); }); } @end

7.系统按键(左字右图)

OC

关键代码

self.getMoreBtn.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;

所有代码

self.getMoreBtn = [UIButton new]; self.getMoreBtn.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft; [self.getMoreBtn setTitleColor:[UIColor colorWithRed:205.0/255.0 green:0.0/255.0 blue:30.0/255.0 alpha:1.0] forState:UIControlStateNormal]; [self.getMoreBtn setImage:[UIImage imageNamed:@"red_rightArrow_normal"] forState:UIControlStateNormal]; [self.getMoreBtn setTitle:@"更多" forState:UIControlStateNormal]; self.getMoreBtn.titleLabel.font = [UIFont systemFontOfSize:14]; // self.getMoreBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 6, 0, -6); self.getMoreBtn.addTo(self.bgView).borderRadius(13).border(1,[UIColor colorWithRed:205.0/255.0 green:0.0/255.0 blue:30.0/255.0 alpha:1.0]).makeCons(^{ make.centerY.equal.view(self.titleLabel); make.right.equal.view(self.bgView).constants(-10); make.height.equal.constants(26); make.width.equal.constants(65); }).onClick(^{ });

Swift

button.semanticContentAttribute = .forceRightToLeft

8.裁切单边圆角

Swift

bgView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询