티스토리 뷰

반응형

Button은 딱 텍스트영역만 Tappable 하다. (노란색은 클릭영역이 아님)

 

 

 

 

이미지를 넣어도 마찬가지로 딱 이미지 영역만 Tappable하다.  (노란색은 클릭영역이 아님)

 

 

 

 

 

UIKit과 달리 SwiftUI에서는 버튼을 만들기 위해서 Label이라고 불리는 다른 뷰를 꼭 줘야한다.

그래서 Label 영역만 tappable하게 디자인되었나보다. (추측)

 

 

 

 

그러면 Label말고 다른 영역도 Tappable하게 하려면 어떻게 해야할까?!

 

[1] Button말고 Label에 frame을 주기 

Label영역만 Tappable하니까 Label영역을 버튼사이즈로 해주면 되는 방법이다. 

 

 

 

 

 

[2] 버튼 아닌 뷰를 만든 후, onTapGesture 사용

SwiftUI의 버튼이 Label 영역만 Tappable하게 디자인 되었다고 하면

버튼이 아닌 뷰를 만들고 onTapGesture를 사용하는 것도 좋은 방법이다.

 

 

 

 

 

[3] 주의사항

Text나 Image에 onTapGesture를 쓴다면 전체영역이 다 tappable 하다. 

하지만 VStack, HStack 같이 뷰를 묶는 container를 쓴다면 

SwiftUI는 container안에서 뭔가 안에 있는 뷰(예를들어 backgroundColor를 가지고 있다거나,,) 에게만 tappable area를 제공한다.

 

 

아래 코드는 HStack의 background color를 clear로 줬다.

텍스트, 이미지만 tappable하고 그외의 stack 영역은 tappable 하지 않다. 

 

 

 

 

하지만 backgroundColor를 yellow로 주면 텍스트, 이미지 그 외의 stack 영역도 tappable하다. 

 

 

 

 

안에 뭐가있든없든 전체 stack을 모두 tappable하게 만들고 싶다면 contentShape를 쓰면 된다. 

stack을 container가 아니라 Rectangle이라는 shape로 인식하게 해서 모든 영역을 tappable하게 하는 것이다. 

 (아래코드는 backgroundcolor가 clear지만 모든 stack영역이 tappable하다)

 

 

 

참고로 이 주의사항은 1번 방법을 쓴다면 고려할 필요없다. 

버튼의 label은 모두 tappable영역이기때문이다. 

(아래코드의 HStack의 모든 영역은 다 tappable하다.)

 

 

 

 

 

 

Reference

www.hackingwithswift.com/quick-start/swiftui/how-to-control-the-tappable-area-of-a-view-using-contentshape

How to control the tappable area of a view using contentShape() - a free SwiftUI by Example tutorial

Was this page useful? Let us know! 1 2 3 4 5

www.hackingwithswift.com

alejandromp.com/blog/playing-with-swiftui-buttons/

Playing with SwiftUI Buttons | Alexito's World

The abstractions on SwiftUI are so composable that customising the UI it's basically an intrinsic property of the framework. Let's take a quick look at some things you can do...

alejandromp.com

stackoverflow.com/questions/56819847/tap-action-not-working-when-color-is-clear-swiftui

stackoverflow.com/questions/57333573/swiftui-button-tap-only-on-text-portion

반응형
댓글