Skip to content

Instantly share code, notes, and snippets.

@usk2000
Created August 8, 2020 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usk2000/bf5bcb172ca072e223dc191006da8cb2 to your computer and use it in GitHub Desktop.
Save usk2000/bf5bcb172ca072e223dc191006da8cb2 to your computer and use it in GitHub Desktop.
カスタムButtonStyle
//: 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