其实最好是用 UIControl来实现不推荐下面的实现方式,重写Button 可能也是个不错的方法,本人还没使用过
3种实现方式:建议重写button实现或者改用UIControll替换
1:重写Button 自己写一个类继承它,然后重写里面的两个函数
-(CGRect)imageRectForContentRect:(CGRect)bounds
{
return CGRectMake(([UIScreen mainScreen].bounds.size.width/4-40)/2, 0, 40, 40);
}
-(CGRect)titleRectForContentRect:(CGRect)bounds
{
return CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width/4, 20);
}
2: 改用UIControll 改控件有响应事件,同时可以向其中添加View
3:下面这种方式比较恶心,但是也可以实现预期的效果
这里默认图片是矩形,其实知道原理了计算起来就简单
效果图:灰色部分为按钮的响应区域
核心代码:为红色,特别注意,如果设置按钮的背景选择了另外的方式则 btn.imageEdgeInsets将无效
//图片都默认为矩形
//当按钮是矩形的时候 即宽 高 一致
CGFloat btnWidth = 44;
CGFloat imgWidth = 25;
CGFloat margin = (btnWidth-imgWidth)/2;
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, btnWidth, btnWidth)];
btn.backgroundColor = [UIColor grayColor];
[btn setImage:[UIImage imageNamed:@"loginHead"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"btn2"] forState:UIControlStateHighlighted];
[btn addTarget:self action:@selector(btnPress) forControlEvents:UIControlEventTouchUpInside];
btn.imageEdgeInsets = UIEdgeInsetsMake(margin, margin, margin, margin);//上、左、下、右
//当按钮是长方形的时候
CGFloat widthBtn = 100;
CGFloat heightBtn = 50;
CGFloat margin_L_R = (widthBtn - imgWidth)/2;
CGFloat margin_U_D = (heightBtn - imgWidth)/2;
UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(70, 145, widthBtn, heightBtn)];
btn2.backgroundColor = [UIColor grayColor];
[btn2 setImage:[UIImage imageNamed:@"loginHead"] forState:UIControlStateNormal];
[btn2 setImage:[UIImage imageNamed:@"btn2"] forState:UIControlStateHighlighted];
[btn2 addTarget:self action:@selector(btnPress) forControlEvents:UIControlEventTouchUpInside];
btn2.imageEdgeInsets = UIEdgeInsetsMake(margin_U_D, margin_L_R, margin_U_D, margin_L_R);//上、左、下、右
[self.view addSubview:btn];
[self.view addSubview:btn2];