SWIFT개발일지

View Modifier

2료일 2023. 12. 14. 18:42

A modifier that you apply to a view or another view modifier, producing a different version of the original value.

- 기존의 뷰 또는  다른 view modifier에 적용시켜 또 다른 버전을 만들 수 있는 modifier이다. 즉 기존의 뷰 또는 modifier에 추가적으로 꾸며줄수 있다.

그런데 여기서 궁금한점... 왜? 굳이 커스텀해서 뷰 모디파이러를 하는가 그자체로 바꾸지 않구?

- 앱 전체적으로 쓰이는 스타일이 있다면 일일이 수정해주려면 코드를 일일이 추가해주어야하기에

struct RedBorder: ViewModifier {
    func body(content: Content) -> some View {
        content
            .border(Color.red, width: 1)
    }
}
Text("Hello, world!")
    .modifier(RedBorder())

이런식으로 한번에 텍스트를 내가 원하는 방식으로 커스텀이 가능해진다.

 

 

아니면 view의 확장을 이용할수도 있다. 

extension View {
	func borderRed() -> some View {
    	modifier(RedBorder())
 }
 struct ContentView: View {
 	var body: some View {
    	Text("hi")
        	.borderRed()
    }
}

위와 같은 방법 아니면

extension View {
func borederRed() -> some View {
    self.
        foregroundColor(Color.red)
       }
}
       
struct ContentView: View {
	var body: some View{
		Text("Red")
			.borederRed()
}}

이것도 아니면 새로운 뷰로 빼는 방법도 있다.

struct BorderRed<Content: View>: View {
  let content: Content
  init(@ViewBuilder content:() -> Content) {
    self.content = content()
    }
    var body: some View {
    	content
          .overlay(
             RoundedRectangle(cornerRadius: 14)
                .stroke(lineWidth: 1)
                )
        	.foregroundStyle(Color.red)
    }
}
struct ContentView: View {
  var body: some View {
    BorderRed(content:{Text("red")})}}

어떤 방법으로 할지는 팀원과의 조율하면 된다.  

1. 하나의 뷰모디파이어로 만들어서 호출

2. 메소드로 만들어서 호출

3. 하나의 struct로 만들어서 호출 

하지만 결국 공통된것을 하나로 만들어서 쉽게 호출할수 있는 것!