Created
August 8, 2020 02:53
-
-
Save usk2000/bf5bcb172ca072e223dc191006da8cb2 to your computer and use it in GitHub Desktop.
カスタムButtonStyle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: A UIKit based Playground for presenting user interface | |
import UIKit | |
import PlaygroundSupport | |
import SwiftUI | |
struct ContentView: View { | |
/// 通常のボタン | |
var normalButtonStyle: CustomButtonStyle = .init(isEnabled: true, cornerRadius: 10, color: .blue, disabledColor: .gray, textColor: .white) | |
/// 無効のボタン | |
var disabledButtonStyle: CustomButtonStyle = .init(isEnabled: false, cornerRadius: 10, color: .blue, disabledColor: .gray, textColor: .white) | |
/// 角丸のボタン | |
var roundedButtonStyle: CustomButtonStyle = .init(isEnabled: true, cornerRadius: .infinity, color: .blue, disabledColor: .gray, textColor: .white) | |
var body: some View { | |
VStack { | |
Button(action: { debugPrint("button pressed") }) { | |
HStack { | |
Image.init(systemName: "plus") | |
Text("ボタン") | |
} | |
.padding() | |
}.buttonStyle(normalButtonStyle) | |
Button(action: { debugPrint("button pressed") }) { | |
HStack { | |
Image.init(systemName: "plus") | |
Text("ボタン") | |
} | |
.padding() | |
}.buttonStyle(disabledButtonStyle) | |
.disabled(true) | |
Button(action: { debugPrint("button pressed") }) { | |
HStack { | |
Image.init(systemName: "plus") | |
Text("ボタン") | |
} | |
.padding() | |
}.buttonStyle(roundedButtonStyle) | |
} | |
} | |
} | |
struct CustomButtonStyle: ButtonStyle { | |
@State var isEnabled: Bool //ボタン有効・無効 | |
var cornerRadius: CGFloat //角丸半径 | |
var color: Color //通常Color | |
var disabledColor: Color //無効Color | |
var textColor: Color //テキストcolor | |
func makeBody(configuration: Configuration) -> some View { | |
let isPressed = configuration.isPressed | |
let foregroundColor = isEnabled ? color : disabledColor | |
return configuration.label | |
.background(RoundedRectangleFill.init(cornerRadius: cornerRadius, fillColor: foregroundColor)) | |
.foregroundColor(textColor) | |
.shadow(color: foregroundColor, radius: 5, x: 0, y: 0) | |
.scaleEffect(x: isPressed ? 0.95 : 1, y: isPressed ? 0.95 : 1, anchor: .center) | |
.animation(.spring(response: 0.2, dampingFraction: 0.9, blendDuration: 0)) | |
} | |
} | |
/// 角丸の四角形 | |
struct RoundedRectangleFill: View { | |
var cornerRadius: CGFloat //角丸の半径 | |
var fillColor: Color //Fillする色 | |
var body: some View { | |
return RoundedRectangle(cornerRadius: cornerRadius) | |
.foregroundColor(fillColor) | |
} | |
} | |
// Present the view controller in the Live View window | |
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment