以 2:1 的比例定义上边是图片,下边是文字的按钮,废话不多说,直接上代码哟:
import UIKit
class TopImageButton: UIButton {
override init(frame: CGRect) {
super.init(frame:frame)
//图片居中显示
self.imageView?.contentMode = .Center
//文字居中显示
titleLabel?.textAlignment = .Center
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//定义图片所在的坐标范围
override func imageRectForContentRect(contentRect: CGRect) -> CGRect {
return CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height/3*2)
}
//定义文字所在的坐标范围
override func titleRectForContentRect(contentRect: CGRect) -> CGRect {
return CGRect(x: 0, y: frame.size.height/3*2, width: frame.size.width, height: frame.size.height/3)
}
}