如何使UIView可点击

zzz*_*zzz 11 objective-c uiview uiimageview uilabel ios6

我有一个包含UILabel和UIImageView的自定义UIView.如何使我的UIView可点击?我想在用户开始按下UIView的任何时候改变UIView的背景.当用户抬起按钮时,颜色应该会改变.我还需要能够处理click事件.

Kas*_*ame 20

-(void)addGestureRecogniser:(UIView *)touchView{

    UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changecolor)];
    [touchView addGestureRecognizer:singleTap];
    DBLog(@"ADD GESTURE RECOGNIZER");
}
-(void)changecolor{

  // do something


}
Run Code Online (Sandbox Code Playgroud)

1`)这是代码片段,你需要将视图作为参数传递,以使其可点击.


K.K*_*K.K 10

另一种方法是通过storyboard/Interface Builder连接手势识别器.

我觉得这比使用代码更简单.

以下是设置Gesture Recognizer的逐步参考.只需搜索Gesture Recognizer:

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html#//apple_ref/doc/uid/TP40015214-CH6-SW1

在此处列出以上链接的步骤:

  1. 将Tap Gesture Recognizer对象拖到Object library场景中,然后将其放在UIView的顶部.
  2. 您将在用餐中看到Tap Gesture Recognizer scene dock.场景底座是故事板中View Controller的顶部,您可以在其中找到First Responder,Exit等.
  3. 通过从场景底座中的手势识别器拖动到代码显示,将Tap Gesture Recognizer连接到您的代码.像对待UIButton操作一样填充Action对话框.
  4. 你完成了!:d


Phi*_*hil 6

Swift 2.0版本:

不要忘记实现UIGestureRecognizerDelegate

// Add tap gesture recognizer to View
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("onClickOnView"))
tapGesture.delegate = self
self.view.addGestureRecognizer(tapGesture)

func onClickOnView(){
   print("You clicked on view..")
}
Run Code Online (Sandbox Code Playgroud)

Swift 3.0版本:

// Add tap gesture recognizer to View
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(clickView(_:)))
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)

func clickView(_ sender: UIView) {
    print("You clicked on view")
}
Run Code Online (Sandbox Code Playgroud)