Trying to a create a custom frame for background image in UIButton for UIViewRepresentable

Viewed 52

I am trying to create a custom frame for a background image on my UIButton. Here is my code so far:

struct MSButton: UIViewRepresentable {
    
    var label: String
    var action: (() -> Void)?
    
    init(_ label: String, action: @escaping () -> Void) {
        self.label = label
        self.action = action
    }
    
    func makeUIView(context: Context) -> UIButton {
        let button = UIButton()
                
        button.setTitle(label, for: .normal)
        button.setBackgroundImage(UIImage(named: "button.png"), for: .normal) // Where I'm trying to add the custom frame.
        
        return button
    }
    
    func updateUIView(_ uiView: UIButton, context: Context) {
        
    }
}

How would I go about doing this? Currently, the preview just shows the background image stretching to the entire screen.

1 Answers

I have a lot of trouble with the problem but here’s what I managed to do

struct MSButton: UIViewRepresentable {

var label: String
var imagesize: CGSize
var action: (() -> Void)?

init(_ label: String, action: @escaping () -> Void, imagesize: CGSize) {
    self.label = label
    self.action = action
    self.imagesize = imagesize
}

func makeUIView(context: Context) -> UIButton {
    let image = UIImage(named: "button.jpeg")
    
    let resized = image?.resizeImageTo(size: imagesize)
    let button = UIButton()

    button.setTitle(label, for: .normal)
    button.setTitleColor(.red, for: .normal)
    button.setBackgroundImage(resized, for: .normal) // Where I'm trying to add the custom frame.
    button.clipsToBounds = true

    button.layer.cornerRadius = 10
    return button
}

func updateUIView(_ uiView: UIButton, context: Context) {
    
}
}


extension UIImage {
func resizeImageTo(size: CGSize) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    self.draw(in: CGRect(origin: CGPoint.zero, size: size))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return resizedImage
}
}

struct ContentView: View {

var size = CGSize(width: 200, height: 100)

var body: some View {
        MSButton("Button", action: { 
            
        }, imagesize: size)
        .frame(width: size.width, height: size.height)
}
}

enter image description here

Related