gpt4 book ai didi

ios - UITapGestureRecognizer initWithTarget :action: method to take arguments?

转载 作者:技术小花猫 更新时间:2023-10-29 10:44:35 28 4
gpt4 key购买 nike

我正在使用 UITapGestureRecognizer,因为我正在使用一个 UIScrollView 作为我的 UILabel 的容器。基本上我正在尝试使用带有参数的操作方法,这样我就可以,例如将 myLabel.tag 值发送到操作方法,以根据点击触发的 UILabel 了解要采取的操作。

一种方法是使用与 UILabel 一样多的操作方法,但这在代码方面并不是很“漂亮”。我想要实现的是只有一种带有 switch 语句的操作方法。

这是可能的还是我必须这样做(叹气):

UITapGestureRecognizer *myLabel1Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel1Tap)];
[myLabel1Tap addGestureRecognizer:myLabel1Tap];

UITapGestureRecognizer *myLabel2Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel2Tap)];
[myLabel1Tap addGestureRecognizer:myLabel2Tap];

UITapGestureRecognizer *myLabelNTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelNTap)];
[myLabel1Tap addGestureRecognizer:myLabelNTap];

- (void)myLabel1Tap {
// Perform action
}

- (void)myLabel2Tap {
// Perform action
}

- (void)myLabelNTap {
// Perform action
}

最佳答案

将单个手势识别器添加到作为各种标签的父 View 的 View 中:

UITapGestureRecognizer *myLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelTapHandler:)];
[myLabelParent addGestureRecognizer:myLabelTap];

然后当你处理手势时,确定哪个标签被点击:

-(void)myLabelTapHandler:(UIGestureRecognizer *)gestureRecognizer {
UIView *tappedView = [gestureRecognizer.view hitTest:[gestureRecognizer locationInView:gestureRecognizer.view] withEvent:nil];

// do something with it
}

关于ios - UITapGestureRecognizer initWithTarget :action: method to take arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6631023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com