SwiftUI ButtonStyleを作成する

角丸ラインのみボタンを作成する。
ViewModifierでやっていたのを、ButtonStyleに変更する。

Style Example
ViewModifier:ButtonDesignModifier
ButtonStyle:RoundedRectangleButtonStyle

Use Example

Button("+1 month", action: {
})
.buttonStyle(RoundedRectangleButtonStyle(adjust: 4.0))
Button("+3 month", action: {
})
.modifier(ButtonDesignModifier(adjust: 4.0))

ViewModifier & ButtonStyle Code

import Foundation
import SwiftUICore
import SwiftUI

struct ButtonDesignModifier: ViewModifier {
    var adjust: CGFloat = 0.0
    
    func body(content: Content) -> some View {
        return content
            .padding(EdgeInsets(top: 8.0 - self.adjust,
                                leading: 16.0 - self.adjust,
                                bottom: 8.0 - self.adjust,
                                trailing: 16.0 - self.adjust))
            .overlay {
                RoundedRectangle(cornerRadius: 8)
                    .stroke(Color.blue, lineWidth: 1)
            }
    }
}

struct RoundedRectangleButtonStyle: ButtonStyle {
    typealias Body = Button

    var adjust: CGFloat = 0.0

    func makeBody(configuration: Configuration) -> some View {
        configuration
            .label
            .foregroundColor(.blue)
            .padding(EdgeInsets(top: 8.0 - self.adjust,
                                leading: 16.0 - self.adjust,
                                bottom: 8.0 - self.adjust,
                                trailing: 16.0 - self.adjust))
            .overlay {
                RoundedRectangle(cornerRadius: 8)
                    .stroke(Color.blue, lineWidth: 1)
            }
    }
}

SwiftSwift,SwiftUI

Posted by shi-n