728x90
https://developer.apple.com/documentation/swiftui/view-styles
View styles | Apple Developer Documentation
Apply built-in and custom appearances and behaviors to different types of views.
developer.apple.com
Label, Button 등의 View에 스타일을 지정하거나 커스텀 할 수 있게 하는 것이 ViewStyle이다.
Label을 예로 들면,,,
기본으로 Label의 style에는 4가지 정도가 있는데, 사용자가 커스텀 해서 스타일을 만들 수 있다.
Custom Style을 만들기 위해서는 LabelStyle 프로토콜을 채택한 구조체를 만들면 된다.
struct TrailingIconLabelStyle: LabelStyle {
func makeBody(configuration: Configuration) -> some View {
HStack {
configuration.title
configuration.icon
}
}
}
LabelStyle을 채택하면 makeBody 함수를 만들어 스타일을 반환시킬 수 있다.
configuration은 LabelStyleConfiguration를 typealias 한 타입으로 Label에 대한 속성을 얻을 수 있다. (title, icon)
Label("Hello", systemImage: "clock")
.labelStyle(TrailingIconLabelStyle())
이렇게 하면 간단하게 커스텀한 스타일을 지정할 수 있다.
extension LabelStyle where Self == TrailingIconLabelStyle {
static var trailingIcon: Self { Self() }
}
또한 LabelStyle에 커스텀한 스타일을 추가해 아래처럼 간단하게 사용할수도 있다.
Label("Hello", systemImage: "clock")
.labelStyle(.trailingIcon)
728x90