Button中UILabel和UIImage的布局
要想很好的完成Button中UILabel和UIImage的布局,我們可以簡單的分成兩步。
- 確定UILabel和UIImage的位置(左右 或者 右左)
- imageEdgeInsets titleEdgeInsets(這里用到的兩個屬性)
- 將兩者看成一個整體完成相應的布局
- contentEdgeInsets(這里用到的屬性)
import UIKit
var str = "Hello, playground"
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
btn.setTitle("Gaol", forState: .Normal)
let image = UIImage(named: "icon_check")
btn.setImage(image, forState: .Normal)
//默認狀態(tài)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
//圖在右邊
let imageWidth = btn.imageView!.bounds.size.width
let labelWidth = btn.titleLabel!.bounds.size.width
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth, bottom: 0, right: -labelWidth)
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth, bottom: 0, right: imageWidth)
btn.contentEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)