2017-08-15 53 views
0

如何以编程方式将按钮标题叠加到按钮图像的顶部,并将它们都定位在相互重叠的按钮框架中的死点?UIButton:以编程方式在图像顶部叠加标题

let button = UIButton() 

button.setImage(coolpic, for .normal) 
button.contentMode = .center 
button.setTitle("tap me", for: .normal) 

// a bunch of constraints and styling that define the frame 

我必须将图像设置为背景图像吗?我是否需要创建一个UILabel作为按钮标题并将其添加为按钮的子视图?

谢谢!

+0

我假设(我从来没有尝试过这一点),你已经通过了使用带有偏移量的罐装'UIButton'等的努力(如果没有,为什么?)所以在我看来,一个简单的子类应该工作。你有没有考虑过这个 – dfd

+0

使用这个button.titleLabel.textAlignment = .Center并将背景图片添加到uibutton –

+0

我应该先说说我是Swift的新手。但这些建议正是我所期待的。 –

回答

0

你可以用图像插图做到这一点,但我喜欢用扩展这样的事情 - 这样我可以在我的应用程序的任何地方使用它们没有子。这是我在一个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) 
0

你可以尝试:

let button = UIButton() 
    button.setImage(UIImage(named:"yourImage.png")?, for: .normal) 

    button.setTitle("MyTitle", for: .normal) 
    button.titleLabel?.font = button.titleLabel?.font.withSize(15) 
    button.titleLabel?.textAlignment = .center 
相关问题