UIbutton設(shè)置圖片和文字

根據(jù)需求,有時(shí)候需要在button上添加圖片和文字,這就需要用到buttontitleEdgeInsetsimageEdgeInsets屬性。用一個(gè)還好,但同時(shí)使用這2個(gè)就感覺控制不好,很多時(shí)候title在圖片下面但不能居中。困擾已久,今天研究了一下,總結(jié)一下。


UIEdgeInsets

typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;

里面的四個(gè)參數(shù)表示距離上邊界、左邊界、下邊界、右邊界的距離,默認(rèn)都為零,title/image在button的正中央


先上代碼 , 使用的圖片的像素是55 * 55

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor orangeColor];
    btn.frame = CGRectMake(100, 100, 80, 80);
    [btn setImage:[UIImage imageNamed:@"致電我們-圖標(biāo)"] forState:0];
    [btn setTitle:@"1234" forState:0];
    [btn setTitleColor:[UIColor whiteColor] forState:0];
    
    [btn setImageEdgeInsets:UIEdgeInsetsMake(5, 25, 45, 25)];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(50, 0, 5, 0)];
    
    [self.view addSubview:btn];

定義了一個(gè)btn,以為可以顯示正確的button,運(yùn)行一看我錯(cuò)了。文字顯示不出來(lái)。

9E93E830-8405-473C-A364-E7397DA5D971.png

經(jīng)過反復(fù)的測(cè)試,發(fā)現(xiàn)設(shè)置成

[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, -55, 5, 0)];

剛好可以使文字居中且顯示出來(lái);但問題又來(lái)了,圖片的像素一變,文字又跑其他地方去了。所以摸索出最終的解決方法:先根據(jù)圖片設(shè)置文字,再設(shè)置圖片(前提是圖片的像素要比button的像素小,不然還是得按圖片的真是像素來(lái))

[btn setTitleEdgeInsets:UIEdgeInsetsMake(50, -btn.imageView.bounds.size.width, 5, 0)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(5, 25, 45, 25)];
200C4F64-A9CE-402B-90DB-3652DC6D78FD.png

同理如果圖片和文字左右顯示

直接上代碼

    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.backgroundColor = [UIColor orangeColor];
    btn1.frame = CGRectMake(100, 250, 100, 60);
    [btn1 setImage:[UIImage imageNamed:@"致電我們-圖標(biāo)"] forState:0];
    [btn1 setTitle:@"電話" forState:0];
    [btn1 setTitleColor:[UIColor whiteColor] forState:0];
   
    [btn1 setTitleEdgeInsets:UIEdgeInsetsMake(15, -btn1.imageView.bounds.size.width + 40, 15, 0)];
    [btn1 setImageEdgeInsets:UIEdgeInsetsMake(10, 5, 10, 55)];   //40 * 40
    
    [self.view addSubview:btn1];

顯示


7AB616A1-1BB8-4CB2-BC5A-3FD59A7B16A4.png

總結(jié)

總之,設(shè)置button的這兩個(gè)屬性時(shí),與圖片的真實(shí)像素有關(guān)。如果多個(gè)button的話,最好保證圖片像素是一樣的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容