UIButton *button = [UIButton buttonWithType:0];
[self.view addSubview:button];
button.frame = CGRectMake(20, 120, self.view.bounds.size.width - 40, 60);
button.backgroundColor = [UIColor cyanColor];//背景颜色
[button setTitle:@"button's title" forState:0];//设置标题
button.titleLabel.font = [UIFont systemFontOfSize:18];//设置button文字字体大小
[button setTitleColor:[UIColor blueColor] forState:0];//设置文字颜色
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
-(void)buttonClick:(UIButton *)sender{
NSLog(@"%s",__func__);
}
设置按钮 左对齐、 居中、 右对齐
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft ;//设置文字位置,现设为居左,默认的是居中
//通过设置 title 离边框偏移量 来让title调整到适当的位置
button.contentEdgeInsets = UIEdgeInsetsMake(0/*top*/,10/*left*/, 0/*bottom*/, 0/*right*/);
设置button 圆角
//设置button 圆角
button.layer.cornerRadius = 12.0f;
button.layer.masksToBounds = YES;
当tableview(collectionView )的cell中有一个button按钮 点击button获取当前点击cell的indexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identify = @"RECEIVECELLID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identify];
}
//设置默认值按钮
UIButton *defaultAddress = (UIButton *)[cell viewWithTag:9094];
[defaultAddress addTarget:self action:@selector(setDefaultAddress: event:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
#pragma mark - 设置默认地址
-(void)setDefaultAddress:(UIButton *)sender event:(UIEvent *)event{
NSSet *touchs = [event allTouches];
UITouch *touch = [touchs anyObject];
CGPoint touchPoint = [touch locationInView:self.tableView];
NSIndexPath *currentIndexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
_current_SelectIndex = currentIndexPath.row;
}
当button的类型设置为 UIButtonTypeSystem
用定时器改变button的标题的时候 button的标题出现闪烁的情况 (获取验证码, 倒计时的时候用到较多)
解决办法 将 button的类型 修改成 UIButtonTypeCustom 即可!
button 设置图片的两种情况
setImage 方法设置图片不会缩放图片 有多大显示多大
setBackgroundImage 方法设置图片会自动缩放比例来适应 button的大小
UIImage *image = [UIImage imageNamed:@"image"];
[button setImage:image forState:0];
效果图:
Simulator Screen Shot 2016年9月1日 下午5.11.33.png
UIImage *image = [UIImage imageNamed:@"image"];
[button setBackgroundImage:image forState:0];
效果图:
Simulator Screen Shot 2016年9月1日 下午5.13.00.png