用UIButton的titleEdgeInsets屬性和 imageEdgeInsets屬性實現圖片文字按要求排列,

來源:互聯網
上載者:User

用UIButton的titleEdgeInsets屬性和 imageEdgeInsets屬性實現圖片文字按要求排列,
button可以設定 titleEdgeInsets屬性和 imageEdgeInsets屬性來調整其image和label相對位置,具體參考http://stackoverflow.com/questions/4564621/aligning-text-and-image-on-uibutton-with-imageedgeinsets-and-titleedgeinsets/5358259#5358259的第二個答案,關鍵是這個: 這裡說說我自己的理解,理解有誤的地方,大家可以討論 前提:這是在button的frame足夠顯示image和label內容的情況下,如果frame不夠,圖片或者文字會被壓縮(demo的button是xib上畫的,所以大小剛剛好) 前置知識點:titleEdgeInsets是title相對於其上下左右的inset,跟tableView的contentInset是類似的,如果只有title,那它上下左右都是相對於button的,image也是一樣;如果同時有image和label,那這時候image的上左下是相對於button,右邊是相對於label的;title的上右下是相對於button,左邊是相對於image的。 我寫了個demo來說明怎麼設定這兩個屬性以達到自己想要的效果:https://github.com/Phelthas/Demo_ButtonImageTitleEdgeInsets看來說明一下:其中,右邊的是給對應的左邊的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在下,切置中了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.