Notice
Recent Posts
Recent Comments
Link
관리 메뉴

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

[iOS - swift] touch 영역 (터치 영역) 늘리는 방법, point(inside:with:), insetBy(dx:dy:) 본문

iOS 응용 (swift)

[iOS - swift] touch 영역 (터치 영역) 늘리는 방법, point(inside:with:), insetBy(dx:dy:)

jake-kim 2021. 9. 9. 23:07

터치 영역이 늘어난 초록색 버튼

터치 영역 늘리는 아이디어

  • UIView에서 사용하고 있는 point(inside:with:)메소드를 override하여 touch영역 확대
    • point는 터치가 일어난 곳의 좌표이고, event는 gesture의 종류이며, true를 반환하면 point가 receiver의 bounds 내부에 속해있다고 판별 

  • touch 영역 확대는 bounds값을 계산하는 insetBy(dx:dy:) 이용
    • dx, dy가 음수이면 bounds의 크기를 증가, dx, dy가 양수이면 bounds의 크기 감소

  • insetBy(dx:dy:) 자세하게 알아보기: viewDidAppear에서 bounds.insetBy(dx:dy:)로 구한 값으로 bounds재설정 테스트
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 2) {
        print("before rect = \(self.flexibleView.bounds)") // (0.0, 0.0, 100.0, 100.0)
        self.flexibleView.bounds = self.flexibleView.bounds.insetBy(dx: -20, dy: -20)
        print("after rect = \(self.flexibleView.bounds)") // (-20.0, -20.0, 140.0, 140.0)
    }
}
insetBy(dx: -20, dy: -20)
insetBy(dx: 20, dy: -20)
insetBy(dx: -20, dy: 20)
insetBy(dx: 20, dy: 20)

터치 영역 늘리기

터치 영역이 늘어난 초록색 버튼

  • 터치 영역을 증가시킬 버튼들에 공통으로 사용되는 BaseButton에 point(inside:with:) 메소드를 override하여 터치영역 증가
class BaseButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)

        configure()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        super.point(inside: point, with: event)

        /// 모든 방향에 20만큼 터치 영역 증가
        /// dx: x축이 dx만큼 증가 (음수여야 증가)
        let touchArea = bounds.insetBy(dx: -20, dy: -20)
        return touchArea.contains(point)
    }

    func configure() {}
    func bind() {}
}
  • 터치 영역이 늘어난 버튼: BaseButton으로 버튼 생성하여 사용하면 완료
lazy var extendedTouchAreaButton: BaseButton = {
    let button = BaseButton()
    button.setImage(#imageLiteral(resourceName: "addButton"), for: .normal)
    button.backgroundColor = .green.withAlphaComponent(0.5)
    button.addTarget(self, action: #selector(didTapExtendedButton(_:)), for: .touchUpInside)

    return button
}()

* 전체 소스 코드: https://github.com/JK0369/TouchAreaExample

 

* 참고

- point(inside:with:): https://developer.apple.com/documentation/uikit/uiview/1622533-point

- bounds.insetBy(dx:dy:): https://developer.apple.com/documentation/coregraphics/cgrect/1454218-insetby

 

Comments