這里說說我自己的理解,理解有誤的地方,大家可以討論
前提:這是在button的frame足夠顯示image和label內容的情況下,如果frame不夠,圖片或者文字會被壓縮(demo的button是xib上畫的,所以大小剛剛好)
前置知識點:titleEdgeInsets是title相對于其上下左右的inset,跟tableView的contentInset是類似的,
如果只有title,那它上下左右都是相對于button的,image也是一樣;
如果同時有image和label,那這時候image的上左下是相對于button,右邊是相對于label的;title的上右下是相對于button,左邊是相對于image的。
看效果圖來說明一下:
其中,右邊的是給對應的左邊的button及button.imageView, button.titleLabel加上邊框的效果
默認情況下,button的image和label是緊貼著居中的,
那如果想要image在右邊,label在左邊應該怎么辦呢?
答案就是:
self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);
來解釋一下為什么:
其實就是這一句:This
PRoperty is used only for positioning the image during layout
其實titleEdgeInsets屬性和 imageEdgeInsets屬性只是在畫這個button出來的時候用來調整image和label位置的屬性,并不影響button本身的大?。ㄟ@個看第三排的圖比較明顯),
它們只是image和button相較于原來位置的偏移量,那什么是原來的位置呢?就是

這個沒有設置edgeInset時候的位置了。
如要要image在右邊,label在左邊,那image的左邊相對于button的左邊右移了labelWidth的距離,image的右邊相對于label的左邊右移了labelWidth的距離
所以,self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);為什么是負值呢?因為這是contentInset,是偏移量,不是距離
同樣的,label的右邊相對于button的右邊左移了imageWith的距離,label的左邊相對于image的右邊左移了imageWith的距離
所以self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);
這樣就完成image在右邊,label在左邊的效果了。
第三排,image在上,label在下
同樣的第三排調整前的還是第一排的樣子,
跟第一排比起來,image的中心位置向右移動了 CGFloat imageOffsetX = (imageWith + labelWidth) / 2 - imageWith / 2;
上向上移動了 CGFloat imageOffsetY = imageHeight / 2;
所以self.twoButton.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY, imageOffsetX, imageOffsetY, -imageOffsetX);
label的中心位置像左移動了CGFloat labelOffsetX = (imageWith + labelWidth / 2) - (imageWith + labelWidth) / 2;
向下移動了CGFloat labelOffsetY = labelHeight / 2;
所以self.twoButton.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY, -labelOffsetX, -labelOffsetY, labelOffsetX);
然后就大功告成了,現在已經完美實現一個button內image在上,label在下,切居中了