Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swiftUI] Button, ButtonStyle 사용 방법 본문

iOS 기본 (SwiftUI)

[iOS - swiftUI] Button, ButtonStyle 사용 방법

jake-kim 2022. 8. 5. 22:08

목차) SwiftUI의 기본 - 목차 링크

Button 개념

  • Button안에 텍스트를 적고 closure에 액션을 기입
Button("MyButton") { print("did tap") }
  • action을 앞에서 받고 뒤에 Text와 같은 컴포넌트를 넣어서 표출도 가능
    • 색상은 systemBlue가 디폴트로 설정
Button(action: { print("tap button!") }) {
  Text("MyButton")
}
  • action에 클로저로 넣어도 되지만, 일반 func 함수를 넣어도 가능
struct ContentView: View {
  var body: some View {
    Button(action: self.didTapButton) { // <-
      Text("MyButton")
    }
  }
  
  func didTapButton() {
    print("tap button!")
  }
}

ButtonStyle

  • .buttonStyle(_:)로 지정
Button("default") { }
.buttonStyle(.automatic) // default
  • 5가지가 존재
    • .default - 파란색 버튼
    • .plain - 일반 Text 형태 그대로 따라가는 버튼
    • .bordered - 버튼의 tint색상을 기반으로 자동으로 테두리에 어울리는 색상이 생기는 버튼
    • .borderedProminent - 버튼의 tint색상을 기반으로 텍스트가 `눈에 띄도록` 해주는 스타일
    • .borderless - 테두리가 없는 버튼 (= .default와 동일)
VStack {
  Button("default") { }
  .buttonStyle(.automatic) // default

  Button("plain") { }
  .buttonStyle(.plain) // default

  Button("bordered") { }
  .buttonStyle(.bordered)

  Button("borderedProminent") { }
  .buttonStyle(.borderedProminent)

  Button("borderless") { }
  .buttonStyle(.borderless)
}

ex) .bordered와 .borderedProminent 에서 tint색상을 다르게 하면 테두리 색상이 자동으로 그에 어울리는 색상으로 변화

  • VStack의 마지막에 .tint(.purple)을 사용

.bordered와 borderedProminent의 테두리에 자동으로 어울리는 색상이 적용

VStack {
  Button("default") { }
  .buttonStyle(.automatic) // default

  Button("plain") { }
  .buttonStyle(.plain) // default

  Button("bordered") { }
  .buttonStyle(.bordered)

  Button("borderedProminent") { }
  .buttonStyle(.borderedProminent)

  Button("borderless") { }
  .buttonStyle(.borderless)
}
.tint(.purple) // <-
  • buttonStyle 프로토콜을 준수하는 Struct 인스턴스를 .buttonStyle()안에 주입하면 적용되는데, 이 때 자유롭게 버튼을 커스텀하여 사용이 가능

cf) buttonyStyle을 이용한 커스텀 버튼 사용 방법은 다음 포스팅 글 참고

 

* 참고

https://developer.apple.com/documentation/swiftui/primitivebuttonstyle/borderedprominent

https://developer.apple.com/documentation/swiftui/button

Comments