你可以用图像插图做到这一点,但我喜欢用扩展这样的事情 - 这样我可以在我的应用程序的任何地方使用它们没有子。这是我在一个UIButton设置图像位置代码:
extension UIButton {
func setImagePosition(at pos:ButtonImagePosition, withAdjustment adj:CGFloat?) {
let _adj:CGFloat = (adj != nil) ? adj! : 0
let width = frame.size.width
var imgWidth = self.imageView?.frame.size.width
switch pos {
case .center:
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
case .right:
imgWidth = imgWidth! - _adj
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: width - imgWidth!, bottom: 0, right: 0)
case .left:
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: width + imgWidth!)
}
}
}
enum ButtonImagePosition {
case left
case right
case center
}
然后,我把它叫做如下
button.setImagePosition(at: .right, withAdjustment: nil)
我假设(我从来没有尝试过这一点),你已经通过了使用带有偏移量的罐装'UIButton'等的努力(如果没有,为什么?)所以在我看来,一个简单的子类应该工作。你有没有考虑过这个 – dfd
使用这个button.titleLabel.textAlignment = .Center并将背景图片添加到uibutton –
我应该先说说我是Swift的新手。但这些建议正是我所期待的。 –