1. 程式人生 > >iOS經典講解之UIButton改變圖片和文字的位置

iOS經典講解之UIButton改變圖片和文字的位置

作者:劉新林

UIButton的image和titleLabel是靠在一起居中顯示的,預設image在左,titleLabel在右,但是有些情況要求兩者交換位置顯示,可以通過

@property(nonatomic)          UIEdgeInsets imageEdgeInsets;                // default is UIEdgeInsetsZero
@property(nonatomic)          UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero
這兩個屬性來設定。
 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 20, 100, 30);
    [btn setTitle:@"測試" forState:(UIControlStateNormal)];
    [btn setImage:img forState:(UIControlStateNormal)];
    btn.adjustsImageWhenHighlighted = NO;
    [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    btn.backgroundColor = [UIColor blueColor];
    [self.view addSubview:btn];
此時預設顯示的樣式如圖:


如果設定其位置:通過新增程式碼

 CGFloat imgWidth = btn.imageView.bounds.size.width;
 CGFloat labWidth = btn.titleLabel.bounds.size.width;
 [btn setImageEdgeInsets:UIEdgeInsetsMake(0, labWidth, 0, -labWidth)];
 [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -imgWidth, 0, imgWidth)];
其樣式改為:


實現了圖片和文字的位置交換。

道理很簡單,通過調節其偏移量來解決,image相當於左邊偏移了label的寬度距離,右邊相應減少偏移label的距離,titleLabel則相反。