1

I have a textfield and a button. When I click inside the textfield, I want the button to disappear. I defined the textfield as both outlet and action ( with event “Did end on exit”). In the method for the textfield, I have self.testButton.hidden = YES; When I click inside the textfield, the button does not go away. Instead, it remains until I hit the return key on the keyboard – causing the keyboard to go away. I tried the same thing w/ touchup inside as the event on the text field. When you click in the text field, nothing happens to the button.

4

3 回答 3

1

不使用 Target-Action 机制(“Did end on exit”和“Touch Up Inside”),而是使用 Delegate 机制。

首先,让你的类符合UITextFieldDelegate协议。在您的 *.h(头文件)文件中添加以下内容:

// Here I'm assuming your class is inheriting from UIViewcontroller but it
// may be inheriting from some other class. The really important part here 
// is: <UITextFieldDelegate>. That's how you make your class conform to that protocol

@interface THE_NAME_OF_YOUR_CLASS : UIViewController <UITextFieldDelegate>

.

是落实-(void)textFieldDidBeginEditing:(UITextField *)textField方法。另外,请记住也将自己设置为代表self.textField.delegate = self。这样,每次用户开始编辑时都会调用该方法。在那个方法调用里面self.testButton.hidden = YES;。在您的 *.m(实现)文件中添加以下内容:

-(void)viewDidLoad {

    // here I'm assuming you have a 'strong' reference to your text field. 
    // You're going to need one to set yourself as the delegate.
    self.textField.delegate = self;
}

// This is one of the methods defined in the UITextFieldDelegate protocol
-(void)textFieldDidBeginEditing:(UITextField *)textField { 

    self.testButton.hidden = YES;
}

.

同样,要使您的按钮再次出现,请实现该- (void)textFieldDidEndEditing:(UITextField *)textField方法。在其中取消隐藏您的按钮。同样,在您的 *.m 文件中添加以下内容:

// This is another method defined in the UITextFieldDelegate protocol
-(void)textFieldDidEndEditing:(UITextField *)textField {

    self.testButton.hidden = NO;
}

虽然代表现在对你来说可能是个谜,但一旦你熟悉了它们,你就会发现它们很容易。这非常重要,因为 iOS 编程严重依赖委托。

代表是一种基于“好莱坞”原则的“通知”机制,即:不要打电话给我们;我们会打电话给你的。在您的情况下,包含 UITextField 的类有兴趣知道 UITextField 何时开始编辑以及何时结束编辑。但是您的班级不能“轮询”(即不断询问)文本字段以查明状态是否已更改。相反,您使用文本字段注册您的课程,它将是文本字段,它会在发生某些事情时让您知道。这要归功于您实施的方法。

进一步阅读:协议和代表

希望这可以帮助!

于 2013-10-09T20:45:52.217 回答
0

如果您希望按钮在用户开始编辑文本字段时消失,请尝试UIControlEventEditingDidBegin.

于 2013-10-09T20:45:14.800 回答
0

您是否确保 testButton 在隐藏它之前设置了它的 IBOutlet ?

于 2013-10-09T20:42:46.117 回答