交換Button中圖片與文字左右位置
默認情況下,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);