iOS Button 上文字圖片位置的設定
阿新 • • 發佈:2019-01-05
建立一個 UIButton
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; button.backgroundColor = [UIColor grayColor]; [button setImage:[UIImage imageNamed:IMAGE] forState:UIControlStateNormal]; [button setTitle:TITLE forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; button.frame = CGRectMake(0, 0, 100, 50); button.center = self.view.center; [self.view addSubview:button];
UIButton的預設佈局是:title在右,image在左;
想要修改UIButton的文字位置和圖片顯示的位置就要藉助一個非常重要的屬性
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;
表示
上 左 下 右的偏移量;解釋下,這四個量的含義:
top : 為正數的時候,是往下偏移,為負數的時候往上偏移;
left : 為正數的時候往右偏移,為負數的時候往左偏移;
bottom : 為正數的時候往上偏移,為負數的時候往下偏移;
right :為正數的時候往左偏移,為負數的時候往右偏移;
實現標題在左 圖片在右
CGSize titleSize = button.titleLabel.bounds.size; CGSize imageSize = button.imageView.bounds.size; CGFloat interval = 1.0; button.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval)); button.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageSize.width + interval), 0, imageSize.width + interval);
實現圖片在上 文字在下
CGSize titleSize = button.titleLabel.bounds.size;
CGSize imageSize = button.imageView.bounds.size;
CGFloat interval = 1.0;
[button setImageEdgeInsets:UIEdgeInsetsMake(0,0, titleSize.height + interval, -(titleSize.width + interval))];
[button setTitleEdgeInsets:UIEdgeInsetsMake(imageSize.height + interval, -(imageSize.width + interval), 0, 0)];