交換Button中圖片與文字左右位置

交換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);

這樣就完成image在右邊,label在左邊的效果了。

發佈了47 篇原創文章 · 獲贊 11 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章