OC之UIbutton

SONG / 文 发表于2018-01-24 17:58 次阅读 uibutton
@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//动态创建我们自己的按钮

//1.创建按钮(UIButton)
UIButton *button = [[UIButton alloc]init];

//2.设置按钮上显示的文字
[button setTitle:@"点我一下吧" forState:UIControlStateNormal];
[button setTitle:@"摸我一下吧" forState:UIControlStateHighlighted];

//设置文字颜色
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];

//3.加载图片
UIImage *imgNormal = [UIImage imageNamed:@"btn_01"];
UIImage *imgHighlighted = [UIImage imageNamed:@"btn_02"];

//4.设置背景图片
[button setBackgroundImage:imgNormal forState:UIControlStateNormal];
[button setBackgroundImage:imgHighlighted forState:UIControlStateHighlighted];

//5.设置frame属性(位置和大小)
button.frame = CGRectMake(50, 50, 100, 100);

//6.通过代码为控件注册一个单机事件
[button addTarget:self action:@selector(buttonPrint) forControlEvents:UIControlEventTouchUpInside];

//7.把动态创建的控件添加到控制器的view中
[self.view addSubview:button];

}

- (void)buttonPrint{

   printf("测试打印");
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

1.UIButton在不同状态下的设置:

UIControlStateNormal 正常状态

UIControlStateHighlighted 高亮状态,按钮按下时状态,在正常状态时按下

UIControlStateSelected 选中状态

UIControlStateDisabled 禁用状态

UIControlStateReserved 保留状态

UIControlStateSelected|UIControlStateHighlighted 高亮状态,按钮按下时状态,在选中状态时按下

例如:

     [btn setImage:  forState:UIControlStateNormal];

    [btn setImage:  forState:UIControlStateHighlighted];

    [btn setImage:  forState:UIControlStateSelected];

    [btn setImage:  forState:UIControlStateSelected|UIControlStateHighlighted];

2.UIButton类型: UIButtonTypeCustom 自定义类型

UIButtonTypeRoundedRect 圆角类型

UIButtonTypeDetailDisclosure 细节展示按钮

UIButtonTypeInfoLight 浅色背景的信息按钮

UIButtonTypeInfoDark 暗色背景的信息按钮

UIButtonTypeContactAdd 添加按钮

3.特殊实例:

1.让UIButton的title居左对齐,我们设置 :

    btn.textLabel.textAlignment = UITextAlignmentLeft

是没有作用的,我们需要设置 :

    btn.contentHorizontalAlignment = UIControlContentHorizonAlignmentLeft;

但是问题又出来,此时文字会紧贴到左边框,我们可以设置 :

btn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);

使文字距离左边框保持10个像素的距离。 纯属自己学习之时,怕遗忘,以此留作记忆。

收藏 赞 (1) 踩 (0)