iOS开发系列之一 – UIButton 用法小结

// 初始化按钮并设置类型
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

// 能够定义的UIButton类型有以下6种:
//    typedef enum {
//        UIButtonTypeCustom = 0,          自定义风格
//        UIButtonTypeRoundedRect,         圆角矩形
//        UIButtonTypeDetailDisclosure,    蓝色小箭头按钮,主要做详细说明用
//        UIButtonTypeInfoLight,           亮色感叹号
//        UIButtonTypeInfoDark,            暗色感叹号
//        UIButtonTypeContactAdd,          十字加号按钮
//    } UIButtonType;

// 设置按钮大小和位置
btn.frame = CGRectMake(20, 360, 280, 45);
// 设置按钮背景颜色
btn.backgroundColor = [UIColor colorWithRed:254/255.0f green:254/255.0f blue:254/255.0f alpha:1.0f];
// 设置按钮文字
[btn setTitle:@"Normal" forState:UIControlStateNormal];
[btn setTitle:@"Pressed" forState:UIControlStateHighlighted];

// forState这个参数的作用是定义按钮的文字或图片在何种状态下才会显现,以下是几种状态:
//    enum {
//        UIControlStateNormal       = 0,           常规状态显现
//        UIControlStateHighlighted  = 1 << 0,      高亮状态显现
//        UIControlStateDisabled     = 1 << 1,      禁用的状态才会显现
//        UIControlStateSelected     = 1 << 2,      选中状态
//        UIControlStateApplication  = 0x00FF0000,  当应用程序标志时
//        UIControlStateReserved     = 0xFF000000   为内部框架预留,可以不管他
//    };

// 设置按钮文字颜色
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
// 设置按钮文字字体
[btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
[btn.layer setMasksToBounds:YES];
// 设置按钮四个圆角半径
[btn.layer setCornerRadius:4.0];
// 设置按钮边框宽度
[btn.layer setBorderWidth:0.5];
// 设置按钮边框颜色
CGColorRef colorref = CGColorCreate(CGColorSpaceCreateDeviceRGB(),(CGFloat[]){168/255.0f, 168/255.0f, 168/255.0f, 1.0});
[btn.layer setBorderColor:colorref];
// 去除按钮在叠加视图中的按下延迟
tableView.delaysContentTouches = NO;
// 添加点击事件
[btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

// 在视图中显示按钮
[tableView addSubview:btn];

// 按钮点击事件
- (void)btnAction:(id)sender
{
    // do something
}

暂无评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

验证码已失效,请刷新验证码