【问题标题】:change UIButton default action by gesture recognizer通过手势识别器更改 UIButton 默认操作
【发布时间】:2016-10-19 13:31:34
【问题描述】:

看不懂Event Handling Guide for iOS-Interacting with Other User Interface Controls里的表达方式

如果您有这些控件之一的自定义子类并且想要更改 >default 操作,请将手势识别器直接附加到控件而不是 > 父视图。然后,手势识别器首先接收到触摸事件。

谁能给我一些例子?谢谢

【问题讨论】:

  • 声明似乎很清楚。将手势识别器显式添加到您的特定控件。我不确定为什么它甚至必须是自定义控件。我只是尝试这样做,看看它是否有效。

标签: ios iphone uibutton


【解决方案1】:

子类UIButton 附加手势识别器。

在 CustomButton.m 中

#import "CustomButton.h"

@implementation CustomButton

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
                                              initWithTarget:self action:@selector(handleTap)];
        tapGesture.numberOfTapsRequired = 2;
        [self addGestureRecognizer:tapGesture];
    }
    return self;
}

- (void)handleTap
{
    NSLog(@"Button tapped twice");
}

在您的 ViewController 中启动按钮并添加为子视图

#import "ViewController.h"
#import "CustomButton.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    CustomButton *customButton = [[CustomButton alloc] initWithFrame:CGRectMake(100.0f, 100.0f, 150.0f, 100.0f)];
    [customButton setTitle:@"Tap Twice" forState:UIControlStateNormal];
    customButton.backgroundColor = [UIColor grayColor];
    [self.view addSubview:customButton];

}

通常按钮在单击时工作。我们正在通过将点击手势识别器和点击次数增加 2 来更改按钮的默认行为。

【讨论】:

  • 非常感谢!!我误解了“父视图”,我以为是按钮(orz)
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 2011-06-17
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多