如何使按钮的圆圈区域可以单击,而不是整个原始矩形

时间:2015-09-11 21:13:55

标签: ios swift uibutton cgrect cornerradius

我有一个方法可以在UIImageView上绘制一个圆形按钮。按钮看起来很棒并且完美地执行。然而,它的可点击区域不仅仅是为它绘制的圆,而是整个原始矩形。

以下是DrawMenu类中的按钮方法:

func drawButton(superImageView: UIImageView, delegate: ButtonDelegate, x_of_origin: CGFloat, y_of_origin: CGFloat, width_of_oval: CGFloat, height_of_oval: CGFloat, want_to_test_bounds:Bool) -> UIButton {

    var button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    button.addTarget(delegate, action: "buttonTap:", forControlEvents: UIControlEvents.TouchUpInside)

// THIS IS WHERE THE ORIGINAL RECT IS DEFINED, and it currently the clickable area
    button.frame = CGRect(x: x_of_origin, y: y_of_origin, width: width_of_oval, height: height_of_oval)

    button.clipsToBounds = true

 // This is where the look of circle is defined, and IS WHERE THE CLICKABLE AREA SHOULD BE 
    button.layer.cornerRadius = height_of_oval/2.0

    if (want_to_test_bounds == true) {
        button.layer.borderColor = UIColor.blackColor().CGColor
        button.layer.borderWidth = 1.0
    }
    return button
}

这是ViewController中的调用:

override func viewDidLoad() {
    super.viewDidLoad()

    var drawMenu = DrawMenu()

    var newButton = drawMenu.drawButton(imageView, delegate: self, x_of_origin: 100, y_of_origin: 150, width_of_oval: 100, height_of_oval: 100, want_to_test_bounds: true)
    imageView.userInteractionEnabled = true
    imageView.addSubview(newButton)
}

与往常一样,任何帮助表示赞赏。谢谢

编辑后,标记为[重复]

我很感激问题 iOS:按钮的非方形命中区问的是基本相同的问题,我很感激被引导到它。

然而,经过几个小时的争论,我相信所提问题的唯一解决方案是:

"您可以通过继承UIButton并提供自己的:

来实现这一目标
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
// return YES if point is inside the receiver’s bounds; otherwise, NO.
}

Apple的UIView文档提供了详细信息,例如确认该点已经在接收器的坐标系中。"

是不够的,因为它与我的问题的额外困难有关。

具体做法是:

 1.什么是接收者的界限"在这种情况下?     它不能与原始rect相关,因为这会给我相同的结果。因此它可能是return button

 即使是这样,我怎么能实现呢? pointInside:无法接受额外的论点。

 3.我也在不同的类中实现这一点,这进一步区分了我上面给出的解决方案。

我理解避免重复问题的重要性。但是在这种情况下,我认为要求提供一个更好的解决方案是不合理的,因为 iOS:按钮的非方形命中区域

再次感谢你。

0 个答案:

没有答案