[英]How to restrict my objects to call a method only once in iOS?
我有五个textfields
和一种动画方法。 我只想在textfield
每次单击上调用一次动画方法(因此基本上总共要调用五次,而每个textfield
只能调用一次)。 我已经尝试过,但是无法找出正确的方法来做。 请帮我。 任何帮助都将不胜感激。
您需要为每个textField接受五个布尔变量。
BOOL flag1;
BOOL flag2;
BOOL flag3;
BOOL flag4;
BOOL flag5;
默认情况下,它的值为false。 因此,如下所述在textField的委托方法textFieldShouldBeginEditing上使其成立,并为每个textField分配标签1,2,3 ..,5。
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if(textField.tag == 1) {
if(flag1 == FALSE) {
//Call Animation method over here..
}
flag1 = TRUE;
} else if (textField.tag == 2) {
if(flag2 == FALSE) {
//Call Animation method over here..
}
flag2 = TRUE;
} else if //.......... and so on for other three textfields..
}
如果我理解正确,您可能只想为每种五个按钮的按钮单击设置某种类型的标志。 因此,如果单击了按钮一,请将按钮一的标志设置为是。 然后确保仅在按钮标志=否时触发动画。
您将在Controller中需要五个属性:
var isTextField1Played = false
var isTextField2Played = false
var isTextField3Played = false
var isTextField4Played = false
var isTextField5Played = false
在click方法中,编写:
func click1() {
if isTextField1Played == true {
return
}
//Animation code
isTextField1Played = true
}
虽然可接受的答案是正确的并且可以正常工作,但是管理起来有点繁琐,不必要地扩大了视图控制器代码。 另一种方法是将UITextField
子类化:甚至是像这样简单的东西:
CustomTextField.h:
#import <UIKit/UIKit.h>
@interface CustomTextField : UITextField
@property (nonatomic, assign) BOOL hasAlreadyAnimated;
@end
CustomTextField.m:
#import "CustomTextField.h"
@implementation CustomTextField
@end
实际上,实现文件可以保留为空,因为我们只关心添加的属性,并且默认情况下会将其初始化为NO
。
这样可以将您的委托方法简化为:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if ([textField isKindOfClass:[CustomTextField class]) { // sanity check, also needed if you want to have some non-animatable text fields
CustomTextField *customTF = (CustomTextField *)textField;
if (customTF.hasAlreadyAnimated == NO) {
//your animation code
}
customTF.hasAlreadyAnimated = YES;
}
}
这种方法的另一个好处是,如果您决定更改可设置动画的文本字段的数量,则无需添加/删除这些标志。
此类可在代码中和Interface Builder中使用-如果您不知道如何检查此线程 。
在情节提要中为文本字段分配标签1,2,3,4,5..etc,并检查以下条件并分配新的标签值。 使用以下代码,您不需要任何额外的变量或新的自定义类。
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if(textField.tag < 100) { //if you think there may be possibility for more than 100 text fields you can change.
textField.tag += 100;
//call Animation method here.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.