【问题标题】:Tappable zone for UIImageView with rounded corners UIKit带有圆角 UIKit 的 UIImageView 的可点击区域
【发布时间】:2021-02-21 22:38:20
【问题描述】:

我遇到了一个有趣的问题 - 有一个带圆角的方形 UIImageView(使它成为一个圆形),我做到了,所以每当您触摸视图时,都会发生一些事情,但问题是圆圈外部和内部的区域视图的框架仍然可以点击,我不知道如何修复它。

要清楚,我希望我的视图只能在圆圈内点击。有办法吗?

这是我的代码 sn-p:

    @IBOutlet weak var profilePictureView: UIImageView? //it is 240x240

    override func viewDidLoad() {
        super.viewDidLoad()
        profilePictureView?.layer.cornerRadius = 240 / 2
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleProfilePictureTap(_:)))
        profilePictureView?.addGestureRecognizer(tap)
        profilePictureView?.isUserInteractionEnabled = true
    }

【问题讨论】:

  • 当然可以。你只需要覆盖hitTest

标签: swift uikit uiimage uigesturerecognizer


【解决方案1】:

将视图控制器指定为识别器的代理,并过滤识别器接收到的触摸:

func viewDidLoad() {
    ...
    tap.delegate = self
}

func gestureRecognizer(_ gr: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    let bezierPath = UIBezierPath(roundedRect: profilePictureView.bounds, cornerRadius: profilePictureView.layer.cornerRadius)
    let point = touch.location(in: profilePictureView)
    return bezierPath.contains(point)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多