Ios 如何将触摸事件添加到UIView?
如何将触摸事件添加到UIView?Ios 如何将触摸事件添加到UIView?,ios,objective-c,events,uiview,touch,Ios,Objective C,Events,Uiview,Touch,如何将触摸事件添加到UIView? 我尝试: 我不想创建一个子类并覆盖它 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 在iOS 3.2及更高版本中,您可以使用手势识别器。例如,这是处理点击事件的方式: //The setup code (in viewDidLoad in your view controller) UITapGestureRecognizer *singleFingerTap = [[
我尝试: 我不想创建一个子类并覆盖它
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
在iOS 3.2及更高版本中,您可以使用手势识别器。例如,这是处理点击事件的方式:
//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];
//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
CGPoint location = [recognizer locationInView:[recognizer.view superview]];
//Do stuff here...
}
还有一些内置的手势。查看有关iOS事件处理和
UIgestureRecognitizer
的文档。我还提供了一些可能会有所帮助的示例代码。我认为您可以简单地使用
UIControl *headerView = ...
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];
我的意思是headerView从UIControl扩展而来。基于您可以定义的宏:
#define handle_tap(view, delegate, selector) do {\
view.userInteractionEnabled = YES;\
[view addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:delegate action:selector]];\
} while(0)
此宏使用ARC,因此没有release
调用
宏使用示例:
handle_tap(userpic, self, @selector(onTapUserpic:));
您可以通过在代码中添加手势识别器来实现这一点 步骤1:ViewController.m:
// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleTap:)];
gesRecognizer.delegate = self;
// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer];
// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
NSLog(@"Tapped");
}
步骤2:ViewController.m:
// Declare the Gesture.
UITapGestureRecognizer *gesRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleTap:)];
gesRecognizer.delegate = self;
// Add Gesture to your view.
[yourView addGestureRecognizer:gesRecognizer];
// Declare the Gesture Recogniser handler method.
- (void)handleTap:(UITapGestureRecognizer *)gestureRecognizer{
NSLog(@"Tapped");
}
注意:在我的例子中,您的视图是@property(强,非原子)ibuiview*localView代码>
编辑:*localView是Main.storyboard中的白色框,从下面开始
这里有一个Swift版本:
// MARK: Gesture Extensions
extension UIView {
func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer (target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
}
func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
userInteractionEnabled = true
}
}
手势识别
有许多常用的触摸事件(或手势),您可以在向视图中添加时收到通知。默认情况下支持以下手势类型:
UITapGestureRecognitor
轻触(短触屏幕一次或多次)
ui长按手势识别器
长时间触摸(长时间触摸屏幕)
ui搜索识别器
平移(在屏幕上移动手指)
UISweepGestureRecognitor
滑动(快速移动手指)
UIPinchGestureRecognitor
按压(将两个手指一起或分开移动-通常用于缩放)
ui旋转手势识别器
旋转(沿圆周方向移动两个手指)
除此之外,您还可以制作自己的自定义手势识别器
在界面生成器中添加手势
将手势识别器从对象库拖到视图上
控件从文档大纲中的手势拖动到视图控制器代码,以进行出口和操作
这在默认情况下应该设置,但也要确保您的视图的用户操作已启用设置为true
以编程方式添加手势
要以编程方式添加手势,您可以(1)创建手势识别器,(2)将其添加到视图,以及(3)创建一个在识别手势时调用的方法
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// 1. create a gesture recognizer (tap gesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
// 2. add the gesture recognizer to a view
myView.addGestureRecognizer(tapGesture)
}
// 3. this method is called when a tap is recognized
@objc func handleTap(sender: UITapGestureRecognizer) {
print("tap")
}
}
注释
//This is my shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//Tap gesture function
func addTapGesture(view: UIView, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
view.addGestureRecognizer(tap)
}
}
sender
参数是可选的。如果你不需要一个手势的参考,那么你可以省略它。但是,如果这样做,请删除操作方法名称后的(发件人:)
handleTap
方法的命名是任意的。使用操作:#选择器(someMethodName(发件人:)
)为其命名
更多例子
您可以研究我添加到这些视图中的手势识别器,看看它们是如何工作的
以下是该项目的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tapView: UIView!
@IBOutlet weak var doubleTapView: UIView!
@IBOutlet weak var longPressView: UIView!
@IBOutlet weak var panView: UIView!
@IBOutlet weak var swipeView: UIView!
@IBOutlet weak var pinchView: UIView!
@IBOutlet weak var rotateView: UIView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Tap
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapView.addGestureRecognizer(tapGesture)
// Double Tap
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapView.addGestureRecognizer(doubleTapGesture)
// Long Press
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gesture:)))
longPressView.addGestureRecognizer(longPressGesture)
// Pan
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(gesture:)))
panView.addGestureRecognizer(panGesture)
// Swipe (right and left)
let swipeRightGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
let swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(gesture:)))
swipeRightGesture.direction = UISwipeGestureRecognizerDirection.right
swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.left
swipeView.addGestureRecognizer(swipeRightGesture)
swipeView.addGestureRecognizer(swipeLeftGesture)
// Pinch
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(gesture:)))
pinchView.addGestureRecognizer(pinchGesture)
// Rotate
let rotateGesture = UIRotationGestureRecognizer(target: self, action: #selector(handleRotate(gesture:)))
rotateView.addGestureRecognizer(rotateGesture)
}
// Tap action
@objc func handleTap() {
label.text = "Tap recognized"
// example task: change background color
if tapView.backgroundColor == UIColor.blue {
tapView.backgroundColor = UIColor.red
} else {
tapView.backgroundColor = UIColor.blue
}
}
// Double tap action
@objc func handleDoubleTap() {
label.text = "Double tap recognized"
// example task: change background color
if doubleTapView.backgroundColor == UIColor.yellow {
doubleTapView.backgroundColor = UIColor.green
} else {
doubleTapView.backgroundColor = UIColor.yellow
}
}
// Long press action
@objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
label.text = "Long press recognized"
// example task: show an alert
if gesture.state == UIGestureRecognizerState.began {
let alert = UIAlertController(title: "Long Press", message: "Can I help you?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// Pan action
@objc func handlePan(gesture: UIPanGestureRecognizer) {
label.text = "Pan recognized"
// example task: drag view
let location = gesture.location(in: view) // root view
panView.center = location
}
// Swipe action
@objc func handleSwipe(gesture: UISwipeGestureRecognizer) {
label.text = "Swipe recognized"
// example task: animate view off screen
let originalLocation = swipeView.center
if gesture.direction == UISwipeGestureRecognizerDirection.right {
UIView.animate(withDuration: 0.5, animations: {
self.swipeView.center.x += self.view.bounds.width
}, completion: { (value: Bool) in
self.swipeView.center = originalLocation
})
} else if gesture.direction == UISwipeGestureRecognizerDirection.left {
UIView.animate(withDuration: 0.5, animations: {
self.swipeView.center.x -= self.view.bounds.width
}, completion: { (value: Bool) in
self.swipeView.center = originalLocation
})
}
}
// Pinch action
@objc func handlePinch(gesture: UIPinchGestureRecognizer) {
label.text = "Pinch recognized"
if gesture.state == UIGestureRecognizerState.changed {
let transform = CGAffineTransform(scaleX: gesture.scale, y: gesture.scale)
pinchView.transform = transform
}
}
// Rotate action
@objc func handleRotate(gesture: UIRotationGestureRecognizer) {
label.text = "Rotate recognized"
if gesture.state == UIGestureRecognizerState.changed {
let transform = CGAffineTransform(rotationAngle: gesture.rotation)
rotateView.transform = transform
}
}
}
注释
//This is my shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//Tap gesture function
func addTapGesture(view: UIView, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
view.addGestureRecognizer(tap)
}
}
- 可以将多个手势识别器添加到单个视图中。不过,为了简单起见,我没有这样做(除了刷卡手势)。如果你需要为你的项目做准备,你应该阅读。这是相当可以理解和有益的
- 以上示例中的已知问题:(1)平移视图在下一个手势事件时重置其帧。(2) 在第一次滑动时,滑动视图来自错误的方向。(不过,我的示例中的这些错误不应影响您对手势识别器工作原理的理解。)
这是一个手势;
首先,在操作下编写以下代码后,需要为GestureRecognizer创建操作,如下所示
- (IBAction)tapgesture:(id)sender
{
[_password resignFirstResponder];
[_username resignFirstResponder];
NSLog(@" TapGestureRecognizer tapped");
}
另一种方法是向视图中添加透明按钮
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
b.frame = CGRectMake(0, 0, headerView.width, headerView.height);
[headerView addSubview:b];
[b addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
然后,单击手柄:
- (void)buttonClicked:(id)sender
{}
Swift 3和Swift 4
import UIKit
extension UIView {
func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
}
使用
yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))
创建一个手势识别器(子类),它将实现触摸事件,如touchsbegind
。之后可以将其添加到视图中
这样,您将使用组合而不是子类化(这是请求)。Swift 3:
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer(_:)))
view.addGestureRecognizer(tapGestureRecognizer)
func handleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {
}
你们为什么不试试
您不需要创建任何手势识别器,也不需要将您的逻辑与其他方法分离SSEventListener
支持在视图上设置侦听器块,以侦听单点击手势、双点击手势和N点击手势(如果愿意)以及长按手势。设置单点击手势侦听器的方式如下:
[view ss_addTapViewEventListener:^(UITapgestureRecognitizer*识别器){…}需要的TapNumberOfTapsRequired:1]
使用UITapGestureRecognitor添加触摸事件
//Add tap gesture to your view
let tap = UITapGestureRecognizer(target: self, action: #selector(handleGesture))
yourView.addGestureRecognizer(tap)
// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
//Write your code here
}
如果要使用SharedClass
//This is my shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//Tap gesture function
func addTapGesture(view: UIView, target: Any, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
view.addGestureRecognizer(tap)
}
}
我的ViewController中有三个视图,分别称为view1、view2和view3
override func viewDidLoad() {
super.viewDidLoad()
//Add gestures to your views
SharedClass.sharedInstance.addTapGesture(view: view1, target: self, action: #selector(handleGesture))
SharedClass.sharedInstance.addTapGesture(view: view2, target: self, action: #selector(handleGesture))
SharedClass.sharedInstance.addTapGesture(view: view3, target: self, action: #selector(handleGesture2))
}
// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
print("printed 1&2...")
}
// GestureRecognizer
@objc func handleGesture2(gesture: UITapGestureRecognizer) -> Void {
print("printed3...")
}
现在看起来很简单。
这是Swift版本
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(tap)
@objc func viewTapped(recognizer: UIGestureRecognizer)
{
//Do what you need to do!
}
目标C:
UIControl *headerView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];
斯威夫特:
let headerView = UIControl(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: nextY))
headerView.addTarget(self, action: #selector(myEvent(_:)), for: .touchDown)
问题是:
如何将触摸事件添加到UIView
这并不是要求举行一次抽头活动
特别是OP想要实现UIControlEventTouchDown
将ui视图
切换到UIControl
是正确的答案,因为手势识别器
对触地
、触碰内部
、触碰外部
等一无所知
此外,UIControl从UIView继承,因此不会丢失任何功能
如果您只需要轻触一下,则可以使用手势识别器。但是如果你想要更好的控制,就像这个问题要求的那样,你需要UIControl
但这会覆盖触摸屏