iOS按鈕設定圖片在上文字在下

來源:互聯網
上載者:User

標籤:

UIButton同時設定Title和Image後,預設是圖片在左文字在右,如1,很多情況下我們希望圖片在片在下,如2,只需要簡單的幾行代碼,即可實現。

 

 

(1)因為需要處理多個按鈕,所以將實現代碼封裝為一個方法,把每個UIbutton執行個體作為參數傳入即可,代碼如下:

 


 
  1. -(void)initButton:(UIButton*)btn{  
  2.     btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使圖片和文字水平置中顯示  
  3.     [btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height ,-btn.imageView.frame.size.width, 0.0,0.0)];//文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度,距離下邊框和右邊框距離不變  
  4.     [btn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,0.0, -btn.titleLabel.bounds.size.width)];//圖片距離右邊框距離減少圖片的寬度,其它不邊  
  5. }  


(2)然後把按鈕傳入

 

 

[objc] view plain copy 
  1. [self initButton:self.btn1];  
  2. [self initButton:self.btn2];  
  3. [self initButton:self.btn3];  
  4. [self initButton:self.btn4];  
  5. [self initButton:self.btn5];  
  6. [self initButton:self.btn6];  
  7. [self initButton:self.btn7];  


(3)運行查看效果。

 

iOS按鈕設定圖片在上文字在下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.