簡體   English   中英

UIButton:以編程方式在圖像上方疊加標題

[英]UIButton: superimpose a title on top of an image programmatically

如何以編程方式將按鈕標題疊加在按鈕圖像的上方,並將它們放置在彼此重疊的按鈕框架中的死點處?

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作為按鈕標題並將其添加為按鈕的子視圖?

謝謝!

您可以嘗試:

    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

您可以使用圖像插圖進行此操作,但是我喜歡對此類事情使用擴展名-這樣,我可以在應用程序中的任何位置使用它們而無需子類化。 這是我在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM