使用场景,iOS实际开发中经常碰到一个按钮图片在上文字在下的UI展示风格,当然实现方法很多种,比如一个imgview一个label等,今天说一个使用系统button的方式,方案如下
按钮创建
NSArray *arr = @[@"待付款",@"待发货",@"待收货",@"待评价"];
NSArray *imgArr = @[@"my_waitpay_icon_",@"my_waitsend_icon_",@"my_waitreceive_icon_",@"wait_waitcomment_icon_"];
CGFloat btnW = APP_WIDTH / arr.count;
for (int i = 0; i < arr.count; i ++) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * btnW, VIEW_BY(self.mySellLB) + 20, btnW, 60)];
[button setTitleColor:Color18 forState:UIControlStateNormal];
[button setTitle:arr[i] forState:UIControlStateNormal];
[button setImage:IMG(imgArr[i]) forState:UIControlStateNormal];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.font = FONT(12);
[button addTarget:self action:@selector(functionClick:) forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
//注意就是这个方法,把我们的普通按钮转成我们需要的按钮
[self initButton:button];
[self.contentView addSubview:button];
}
转换方法
-(void)initButton:(UIButton*)btn{
//使图片和文字水平居中显示
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
[btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height + 20 ,-btn.imageView.frame.size.width, 0.0,0.0)];
//图片距离右边框距离减少图片的宽度,其它不边
[btn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,10, -btn.titleLabel.bounds.size.width)];
}
ps:搞定,如有不足还请指正🙂