按鈕UIButton內圖片和文字位置的設置(兩種方式)


  首先創建一個類,注意需要繼承自UIButton,並在這個類中重寫layoutSubview方法代碼如下(圖片在上,文字在下):

  注:x,y,width,height已經進行封裝過的,封裝方法詳見     http://www.cnblogs.com/hissia/p/5636534.html

 1 - (void)layoutSubviews
 2 {
 3     [super layoutSubviews];
 4     //設置圖片的尺寸
 5     self.imageView.x = 0;
 6     self.imageView.y = 0;
 7     self.imageView.width = self.width;
 8     self.imageView.height = self.imageView.width;
 9     //設置label的尺寸
10     self.titleLabel.x = 0;
11     self.titleLabel.y = self.imageView.height;
12     self.titleLabel.width = self.width;
13     self.titleLabel.height = self.height - self.imageView.height;
14 }

對labe的文字進行處理:

1 - (void)awakeFromNib
2 {
3     [self setup];
4 }
5 - (void)setup
6 {
7     self.titleLabel.textAlignment = NSTextAlignmentCenter;
8 }

如果想以后用這個類創建的Button都具有圖片在上,文字在下面的按鈕,可以添加initWithFrame方法,如下:

1 - (instancetype)initWithFrame:(CGRect)frame
2 {
3     if (self = [super initWithFrame:frame]) {
4         [self setup];
5     }
6     return self;
7 }

 當然了,可以在storyboard或Xib中直接設置。

點擊button按鈕后顯示如圖顯示:

可以選擇image或者label或者content三種,然后下面inset中選擇尺寸


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM