1. 程式人生 > >iOS開發技巧:佈局UIButton的imageView和titleLabel屬性

iOS開發技巧:佈局UIButton的imageView和titleLabel屬性

前言

這是iOS開發技巧系列部落格的第三篇,本篇我主要想給大家分享一下按鈕標題以及圖片檢視的佈局方法。我記得在我初學iOS程式設計做一個專案的時候,有一個檢視上面是圖片,下面是標題的需求,類似於美團的分類,不管點選標題還是圖片,都會觸發事件,看做一個整體。我當時的做法是,封裝一個檢視,新增一個UIButton和一個UIImageView,然後用一個檢視把其覆蓋併為該檢視新增點選手勢,當然,這個檢視是透明的,這樣功能也就實現了,但效果並不理想。後來,我在朋友提示看UIButton標頭檔案的時候,發現有一個imageView屬性,因為當時學習的時候還沒有閱讀標頭檔案的習慣,僅僅只通過titleLabel屬性去設定字型大小而已,並沒有想到會有imageView這個屬性存在。我嘗試著為按鈕設定該屬性,然後我驚奇的發現了標題和圖片都顯示出來了,這樣,一個UIButton就可以搞定當時專案的需求了。只是,這個位置並非是我想要的,因為這樣設定之後圖片居左,文字居右,後來上網查了很多資料,瞭解到通過UIButton的titleEdgeInsets

imageEdgeInsets屬性,可以調整標題和圖片的偏移,管理其佈局。那麼接下來呢,我將結合幾個場景分享通過這兩個屬性佈局按鈕imageView和titleLabel的方法。

場景一:圖片居左,文字居右

預設情況下,titleEdgeInsetsimageEdgeInsets的值為:UIEdgeInsetsZero。是圖片居左,文字居右,垂直居中顯示的,如下圖:

button.titleEdgeInsets = UIEdgeInsetsZero

button.imageEdgeInsets = UIEdgeInsetsZero

這裡寫圖片描述

場景二:圖片居中,文字居中

設定方法如下:

button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -button.imageView!.frame.width, bottom: 0.0, right: 0.0)

button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: -button.titleLabel!.intrinsicContentSize().width)

這裡寫圖片描述

場景三:圖片居上,文字居下,水平居中

設定方法如下:

button.titleEdgeInsets = UIEdgeInsets(top: 0.0
, left: -button.imageView!.frame.width, bottom: -button.imageView!.frame.height, right: 0.0) button.imageEdgeInsets = UIEdgeInsets(top: -button.titleLabel!.intrinsicContentSize().height, left: 0.0, bottom: 0.0, right: -button.titleLabel!.intrinsicContentSize().width)

這裡寫圖片描述

可能你會覺得圖片和文字挨的太緊了,不過沒有關係,我們可通過以下方法將其稍微分開一點。

let offset = 45

button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -button.imageView!.frame.width, bottom: -button.imageView!.frame.height - CGFloat(offset / 2), right: 0.0)

button.imageEdgeInsets = UIEdgeInsets(top: -button.titleLabel!.intrinsicContentSize().height - CGFloat(offset / 2), left: 0.0, bottom: 0.0, right: -button.titleLabel!.intrinsicContentSize().width)

這裡寫圖片描述

場景四:圖片居右,文字居左

設定方法如下:

button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -button.imageView!.frame.size.width - button.frame.size.width + button.titleLabel!.intrinsicContentSize().width, bottom: 0.0, right: 0.0)

button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: -button.titleLabel!.frame.size.width - button.frame.size.width + button.imageView!.frame.size.width)

這裡寫圖片描述

到這裡,本篇的開發技巧分享就結束了,感謝大家的關注與支援,我將繼續更新後續的文章,敬請期待。