使UIImage / UIScrollView的区域“可单击”

mr-*_*-sk 2 iphone uiscrollview uiimageview ipad

所以我有两个问题要解决:

  1. 检测UIImageView中某个区域的单击。
  2. 检测到UIScrollView中某个区域的单击。

我正在考虑两者,因为我有来自客户端的x / y坐标,所以我将以编程方式实例化一个UIButton(自定义/透明)并将其放在UIImageView和UIScrollViews的所需区域上。

当用户选择按钮时,我还会触发一个事件。我正在考虑提供标签并使用像

- (IBAction) btnPress:(id)sender
Run Code Online (Sandbox Code Playgroud)

这样我就可以查询发件人

 [sender tag]
Run Code Online (Sandbox Code Playgroud)

然后根据标签做出决定。每个按钮将具有唯一的ID。我的问题是:

  1. 这是一个好方法吗?有什么会更好?
  2. 我知道如何在IB中完成所有这些操作,但不是以编程方式完成。我的印象是,连接(对于IBActions)仅在IB中进行,因此如何将按钮连接到事件中的所有代码(我将立即开始谷歌搜索)。

TIA。

jus*_*tin 5

如果要使用UIButton处理触摸,则确实可以创建一个自定义按钮以放置在框架上。如果采用此路线,要对按钮应用方法,必须执行以下操作:

UIButton *myButton = [UIButton buttonWithType:....];
myButton.tag = // your tag;
[myButton addTarget:self action:@selector(btnPress:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

然后,当您要调用该方法时,它将是您期望的IBAction方法。

- (IBAction)btnPress:(id)sender {
Run Code Online (Sandbox Code Playgroud)

这里[sender tag]的确会得到你指定的按钮,进入如你所愿。

话虽这么说,我可能更倾向于在视图上设置UIGestureRecognizer。基本上,您将标记UIImageView和/或UIScrollView,然后创建一个手势识别器:

UITapGestureRecognizer *myGesture = [[UITapGestureRecognizer alloc] init];
[myGesture addTarget:self action@selector(frameTouched:)];
// for the case of the imageView;
[myImageView addGestureRecognizer:myGesture];
[myGesture release];
Run Code Online (Sandbox Code Playgroud)

然后要处理手势

- (void)frameTouched:(UIGestureRecognizer *)gesture {
    int myLogicTag = [[gesture view] tag];  // this finds the tag of the view it embodies, in this case your imageView
    // continue with your code;
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您具有自定义的scrollView或imageView类,则可以简单地重写该touchesBegan方法并从中执行所需操作。我认为应该可以很好地涵盖您的选择,因此希望对您有所帮助