要注意的是:
1.titleEdgeInsets是titleLabel相对于其上下左右的inset,跟tableView的contentInset是类似的;
2.如果只有title,那titleLabel的上下左右都是相对于Button的;
3.如果只有image,那imageView的上下左右都是相对于Button的;
4.如果同时有image和label,那image的上下左是相对于Button的,右是相对于label的;
label的上下右是相对于Button的,左是相对于image的。
获取到imageView和titleLabel的宽、高:
CGFloatimageWidth =button.imageView.frame.size.width;
CGFloatimageHeight =button.imageView.frame.size.height;
CGFloatlabelWidth =0.0;
CGFloatlabelHeight =0.0;
if([UIDevicecurrentDevice].systemVersion.floatValue>=8.0) {
//由于iOS8中titleLabel的size为0,用下面的这种设置
labelWidth =button.titleLabel.intrinsicContentSize.width;
labelHeight =button.titleLabel.intrinsicContentSize.height;
}else{
labelWidth =button.titleLabel.frame.size.width;
labelHeight =button.titleLabel.frame.size.height;
}
图上文下:
imageOffsetX= labelWidth/2
imageOffsetY= labelHeight/2 + spacing/2
labelOffsetX= imageWidth/2
labelOffsetY= imageHeight/2 + spacing/2
self.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY, imageOffsetX, imageOffsetY, -imageOffsetX);
self.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY, -labelOffsetX, -labelOffsetY, labelOffsetX);
左文右图:
self.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + spacing/2, 0, -(labelWidth + spacing/2));
self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageHeight + spacing/2), 0, imageHeight + spacing/2);