交換Button中圖片與文字的左右位置
阿新 • • 發佈:2019-02-14
預設情況下,button的image和label是緊貼著居中的,那如果想要image在右邊,label在左邊應該怎麼辦呢?
答案就是:
// 交換button中title和image的位置 CGFloat labelWidth = modelButton.titleLabel.frame.size.width; CGFloat imageWith = modelButton.imageView.frame.size.width; modelButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth); modelButton.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在左邊的效果了。