UIButton作为iOS开发里基本控件,是我们第三个需要学习的。下面我来为大家介绍一下UIButton的一些常用属性和它们的用法。
这里附上UI控件演示的源码地址:https://github.com/LOLR2017/UIKitDemo。源码持续更新中...
因为部分代码是从Xcode直接拷贝出来的样式有误请谅解。
下面是UIButton的基本使用。
//设置按钮正常状态下的标题
[self.firstButton setTitle:@"正常状态" forState:UIControlStateNormal];
//设置按钮选择状态下的标题
[self.firstButton setTitle:@"选择状态" forState:UIControlStateSelected];
//设置按钮高亮状态下的标题
[self.firstButton setTitle:@"高亮状态" forState:UIControlStateHighlighted];
//设置按钮正常状态下的标题颜色
[self.firstButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//设置按钮选择状态下的标题颜色
[self.firstButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
//设置按钮高亮状态下的标题颜色
[self.firstButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];
/*
当然这里如果有需要也可以设置各个状态下的标题图片和背景图片,
这里因为缺少图片资源的关系,这里暂不演示,有兴趣的可以自己试一试。
*/
// [self.firstButton setImage:nil forState:UIControlStateNormal];
// [self.firstButton setBackgroundImage:nil forState:UIControlStateNormal];
//设置标题字体大小
self.firstButton.titleLabel.font = [UIFont systemFontOfSize:16];
//设置标题偏移量
[self.firstButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
/*
设置标题图片偏移量,
*/
// [self.firstButton setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
//给按钮添加点击事件
[self.firstButton addTarget:self action:@selector(firstButtonClick:) forControlEvents:UIControlEventTouchUpInside];
-(void)firstButtonClick:(UIButton *)button {
if (button.isSelected) {
button.selected = NO;
}
else {
button.selected = YES;
}
}
这里附上UI控件演示的源码地址:https://github.com/LOLR2017/UIKitDemo。源码持续更新中...
写在结尾:本文初衷是提供给一些新手或者需要某些资料查询者,代码或者思想有不足之处请大家谅解,希望大家多多原谅。最后希望大家可以共同进步,快乐工作。
上一篇文章:《UILabel的基本使用》
下一篇文章:《UIImageView的基本使用》