UIButton知识点回顾

来源:互联网 发布:知乎名字可以改吗 编辑:程序博客网 时间:2024/05/22 01:52

1、设置UIButton的常见属性:如 标题位置、文字颜色、文字字体、背景色 等

 // 整个按钮的背景色(无背景图片时有效果)  button.backgroundColor = [UIColor grayColor];  // 添加背景图片  [button setBackgroundImage:[UIImage imageNamed:@"enen.png"] forState:UIControlStateNormal];  // 按钮标题  [button setTitle:@"enenenen" forState:UIControlStateNormal];  // 设置按钮上的字体的大小  button.titleLabel.font = [UIFont systemFontOfSize: 14.0];  // button上子控件的水平对齐方式  button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;  // button上子控件的垂直对齐方式  button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;  // 内容容器的偏移,让文字向右偏移15像素  button.contentEdgeInsets = UIEdgeInsetsMake(0,15, 0, 0);  // 设置标题的背景颜色  button.titleLabel.backgroundColor = [UIColor purpleColor];  // 标题颜色  [button setTitleColor:[UIColor blueColor]forState:UIControlStateNormal];  button.imageView.contentMode = UIViewContentModeScaleAspectFit;

注意点:
(1)

// 以如下方式初始化的button,文字默认颜色是白色的,所有如果背景也是白色的话,是看不到文字的;[[UIButton alloc] initWithFrame: CGRectMake(20, 20, 300, 60)];

(2)

// 通过如下方式让UIButton的title居左对齐是无效的button.textLabel.textAlignment = UITextAlignmentLeft// 设置文字位置为居左,默认的是居中button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;// 此时文字会紧贴左边框,我们可以设置其内边距,使文字距离左边框保持15个像素的距离button.contentEdgeInsets = UIEdgeInsetsMake(0,15, 0, 0);

(3)

// 设置UIButton上字体的颜色,不应该使用:[btn.titleLabel setTextColor:[UIColorblackColor]];btn.titleLabel.textColor=[UIColor redColor];// 而是用如下形式:[btn setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];

2、通过继承UIButton,来自定义一个按钮时,可通过重写下面两个函数,来设定自定义按钮中图片和文字的大小以及位置:

-(CGRect) imageRectForContentRect:(CGRect)contentRect ;-(CGRect) titleRectForContentRect:(CGRect)contentRect;

3、 不自定义控件,实现 UIButton 左文字、右图片
下面三种形式的思想是一样的,只是表示形式不同,因为按钮中的图片和文字默认使用的是居中对齐方式,所以采用如下形式;

//(1)button 使用默认的 居中对齐[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -2*btn.imageView.frame.size.width, 0, 0)];[btn setImageEdgeInsets:UIEdgeInsetsMake(0, 2*btn.titleLabel.bounds.size.width, 0, 0)];//(2)button 使用默认的 居中对齐[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 2*btn.imageView.frame.size.width)];[btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -2*btn.titleLabel.bounds.size.width)];//(3)button 使用默认的 居中对齐[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -btn.imageView.frame.size.width, 0, btn.imageView.frame.size.width)];[btn setImageEdgeInsets:UIEdgeInsetsMake(0, btn.titleLabel.bounds.size.width, 0, -btn.titleLabel.bounds.size.width)];

拓展文章: imageEdgeInsets、titleEdgeInsets详解

0 0
原创粉丝点击