gpt4 book ai didi

objective-c - 摇动手势和 firstResponder

转载 作者:行者123 更新时间:2023-11-28 20:39:38 24 4
gpt4 key购买 nike

我正在尝试让摇动手势起作用。这是一些代码

在我的实现文件中

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if(event.type == UIEventSubtypeMotionShake)
{

NSLog(@"Shake gesture detected");

}
}

- (BOOL)canBecomeFirstResponder
{
return YES;
}

我读到,为了使摇动手势起作用,UIView 应该是 firstResponder。这就是我在实现中添加该代码的原因

if(self.view.isFirstResponder)
{
NSLog(@"first");
}
else
{
NSLog(@"no");
}

- (void)viewDidAppear {
[self becomeFirstResponder];
}

当我运行应用程序时,NSLog 的输出为 NO。我想念什么?以及如何让摇动手势起作用

最佳答案

我猜您是在 UIViewController 中执行此操作?那是不正确的......你必须像这样子类化 UIView:

ShakeView.h:

//
// ShakeView.h
//

#import <UIKit/UIKit.h>

@interface ShakeView : UIView {

}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (BOOL)canBecomeFirstResponder;

@end

ShakeView.m:

//
// ShakeView.m
//

#import "ShakeView.h"

@implementation ShakeView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if ( event.subtype == UIEventSubtypeMotionShake ) {
}
if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] ) {
[super motionEnded:motion withEvent:event];
}
}

- (BOOL)canBecomeFirstResponder
{
return YES;
}

@end

然后使用 ShakeView 而不是您的“普通”UIView 并在您的 UIViewController 中实现它:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"Shake happend …");
}

- (void)viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
[super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
[self.view resignFirstResponder];
[super viewWillDisappear:animated];
}

就是这样。希望对您有所帮助:)

关于objective-c - 摇动手势和 firstResponder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9148396/

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