ios - 如何在 UIButton 上触发不同的操作

标签 ios objective-c uibutton

我创建了两个名为 btnFirst 和 btnSecond 的 UIButton。我想根据屏幕将其三角形化,所以我使用 bezire 路径将男性 UIButton 三角形化。我成功了。但是当我点击任何按钮时,两个 UIbutton 操作都会触发。

请帮助我在按钮上触发两个不同的操作

// Build a triangular path
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:(CGPoint){0, 0}];
    [path addLineToPoint:(CGPoint){0, screenHeight}];
    [path addLineToPoint:(CGPoint){screenWidth, 0}];
    [path addLineToPoint:(CGPoint){screenHeight, 0}];
    // Create a CAShapeLayer with this triangular path
    // Same size as the original imageView
    CAShapeLayer *mask = [CAShapeLayer new];
    mask.frame = btnFirst.bounds;
    mask.path = path.CGPath;
    // Mask the imageView's layer with this shape        
    btnFirst.layer.mask = mask;


    UIBezierPath *path1 = [UIBezierPath new];
    [path1 moveToPoint:(CGPoint){0, screenHeight}];
    [path1 addLineToPoint:(CGPoint){screenWidth, 0}];
    [path1 addLineToPoint:(CGPoint){screenWidth, screenHeight}];
    // Create a CAShapeLayer with this triangular path
    // Same size as the original imageView
    CAShapeLayer *mask1 = [CAShapeLayer new];
    mask1.frame = btnSecond.bounds;
    mask1.path = path1.CGPath;
    // Mask the imageView's layer with this shape
      btnSecond.layer.mask = mask1;

以及按钮上的操作

- (IBAction)firstBtnClick:(id)sender {

    NSLog(@"first");
}
- (IBAction)secondBtnClick:(id)sender {
    NSLog(@"second");
}

第一个按钮是灰色的,第二个按钮是绿色的。 enter image description here

最佳答案

问题是,最终所有元素都是某种矩形。因此,在您的情况下,您创建了两个重叠的矩形,它们显示非重叠的三角形。

幸运的是,您不是第一个面临此挑战的人:here是类似问题的答案。虽然它适用于 MacOS,但它应该为您指明正确的方向。

编辑: 因为无论如何你都是用贝塞尔路径绘制三角形,所以有一个比检查 alpha 更简单的解决方案,如我之前发布的链接中所述。

您需要创建自己的 UIButton 类并覆盖 hitTest(_:with:) 方法。

Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.

该类可能如下所示:

class PathButton: UIButton {
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)

        // ensure mask is of type CAShapeLayer, otherwise you won't get access to the path property
        guard let mask = self.layer.mask as? CAShapeLayer else { return hitView }
        // ensure path is set
        guard let path = mask.path else { return hitView }
        // validate if the current touch was within the path
        return path.contains(point) ? hitView : nil
    }
}

只有当触摸位于其路径内时,才会触发自定义按钮的操作。如果没有定义,每次触摸都会触发按钮的操作。

关于ios - 如何在 UIButton 上触发不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895755/

相关文章:

ios - NSObject Delegate类,将Delegate传递给UIViewcontroller类

iphone - AVPlayer 视频 SeekToTime

ios - UIView alpha = 0 导致触摸被放到下面的 View

ios - 如何为 UIButton 设置自定义背景颜色?

ios - 同步多个 AVPlayer

ios - 在 Xcode 7.2 中将 PDF 用于图标图像

ios - JSON 解码器 Swift 的潜在错误

javascript - 如何创建一个延迟非常低的类似短信的系统?

ios - 无法在服务器(SpringBoot)和 iOS 之间建立 WebSocket 连接

ios - 如何以编程方式在 iOS 中并排制作两个 UILabel