簡體   English   中英

如何限制我的對象在iOS中只能調用一次方法?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM