尝试为UIView可表示的UIButton中的背景图像创建自定义边框

uinbv5nw  于 2022-09-19  发布在  Swift
关注(0)|答案(1)|浏览(118)

我正在尝试为我的UIButton上的背景图像创建自定义框架。到目前为止,我的代码如下:

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) {

    }
}

我该如何着手做这件事呢?目前,预览只显示延伸到整个屏幕的背景图像。

vx6bjr1n

vx6bjr1n1#

我在这个问题上遇到了很多麻烦,但以下是我设法做到的

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)
}
}

相关问题