iOS开发 UIButton的创建与使用

2025-06-05 10:57:43

1、创建工程项目和视图控制器 1、创建一个Sing View Application工程项目; 2、为项目命名,生成工程文件。

iOS开发 UIButton的创建与使用

2、初始化UIButton 可以用alloc init,也可以用buttonWithType:;纯代码常用后者。 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [self.view addSubview:button];

iOS开发 UIButton的创建与使用

3、设置位置和使能 [button setFrame:CGRectMake(16, 30, 200, 50)]; [button setCenter:self.view.center]; [button setEnabled:YES];

iOS开发 UIButton的创建与使用

4、设置背景颜色/图片 [button setBackgroundColor:[UIColor blueColor]]; [button setBackgroundImage:[UIImage imageNamed:@".png"] forState:UIControlStateNormal]; [button setBackgroundImage:[UIImage imageNamed:@".png"] forState:UIControlStateHighlighted];

iOS开发 UIButton的创建与使用

5、设置圆角/边框 [button.layer setCornerRadius:5.0]; [button.layer setMasksToBounds:YES]; [button.layer setBorderWidth:3.0]; [button.layer setBorderColor:[[UIColor redColor] CGColor]];

iOS开发 UIButton的创建与使用

6、设置标题/字体/颜色/下划线 NSMutableAttributedString *attributedString = [[NSMutableAttribut髫潋啜缅edString alloc] initWithString:@"属性标题"]; NSRange strRange = {0,[attributedString length]}; [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange]; [button setAttributedTitle:attributedString forState:UIControlStateNormal];

iOS开发 UIButton的创建与使用

7、设置图标 默认30*30大小的。@2x为60*60;@3x为90*90的。

iOS开发 UIButton的创建与使用

8、设置标题和图标偏移 [button setTitleEdgeInsets:UIEdgeInsetsMake(10, 10, 0, 0)]; [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 10, 10)];

iOS开发 UIButton的创建与使用

9、添加目标动作响应 [button addTarget砜实蛰斓:self action:@selector(holdDown蚱澄堆别ButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];- (void)holdDownButtonTouchUpInside:(UIButton *)sender{ NSLog(@"按住按钮触摸到里面");}

iOS开发 UIButton的创建与使用

10、如果您喜欢,请按投票;如果有疑问,欢迎一起探讨。

iOS开发 UIButton的创建与使用
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢