拦截UITextField触摸

时间:2014-03-26 10:14:32

标签: ios objective-c uitextfield uitextfielddelegate uicontrolevents

我想拦截UITextField上的触摸,例如,当我第一次加载它时,我给它@selector()加载一个不同的方法而不是delegate的东西?< / p>

这是我的尝试:

descriptionText = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 25.0, infoView.frame.size.width - 20, 100.0)];
    descriptionText.backgroundColor = [UIColor whiteColor];
    descriptionText.textColor = [UIColor blackColor];
    descriptionText.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    descriptionText.userInteractionEnabled = YES;
    [descriptionText addTarget:self action:@selector(loadInfoView:) forControlEvents:UIControlEventTouchUpInside];
    descriptionText.font = [UIFont fontWithName:@"Helvetica" size:15];
    // show view
    [infoView addSubview:descriptionText];

但是当我调试方法时:

- (void)loadInfoView
{
    NSLog(@"load other view here");
}

2 个答案:

答案 0 :(得分:2)

您的问题出在forControlEvents::尝试UIControlEventEditingDidBegin

[descriptionText addTarget:self action:@selector(loadInfoView:) UIControlEventEditingDidBegin];

如果您有@selector(loadInfoView:)

,那么- (void)loadInfoView也是错误的

@selector(loadInfoView:)- (void)loadInfoView: (id) sender
@selector(loadInfoView)- (void)loadInfoView

但是,为什么不使用UITextFieldDelegate

<强>的.m

@interface ViewController () <UITextFieldDelegate>

    @property (strong, nonatomic) UITextField *descriptionText;

@end

请记住:

self.descriptionText.delegate = self;

,然后

-(void) textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.descriptionText)
    {
        [self loadInfoView];
    }

}

<强>键盘

如果您不想显示键盘,则需要添加[descriptionText resignFirstResponder];

答案 1 :(得分:0)

我不确定您是否可以按照自己的意愿在触摸的文本字段上调用操作。

如果这不起作用,为什么不在文本字段中附加点击手势识别器?