2011-09-06 28 views
0

每次調用視圖時,我都以編程方式爲iOS應用程序視圖創建了2個UITextFeild和1個UIButton。 UIButton調用函數(方法)登錄如何創建一個方法來區分兩個UITextViews?我是一個JS程序員有些來自相同的思維模式有沒有辦法通過一個ID獲取對象?或讓所有UITextFeilds喜歡割裂開來:提前如何處理同一類的多個對象?

-(void)login{ 
Array *UITF[UITFself.view.UITextFeilds]; 
UITF[0].text; 
} 

感謝

UITextField *uname = [[UITextField alloc] initWithFrame:CGRectMake(80.0, 100, 150.0, 30.0)]; 
[uname addTarget:self 
      action:@selector(textFieldDone:) 
    forControlEvents:UIControlEventEditingDidEndOnExit]; 
uname.borderStyle = UITextBorderStyleRoundedRect; 
uname.keyboardType = UITextAutocapitalizationTypeNone; 
uname.returnKeyType = UIReturnKeyDone; 
uname.autocorrectionType = UITextAutocorrectionTypeNo; 
[self.view addSubview:uname]; 

-(void)login { 
    //send login message 
    NSString *u=uname.text;//user name text 
    NSString *p=pass.text;//password text 
    NSLog(u); 
    NSLog(p); 

} 
+1

這裏有一個問題:'UITextView'和'UITextField'是不同的類,'UITextFeild'是拼寫錯誤。 – PengOne

回答

1

做最簡單的事情是在頭宣佈UITextField S:

UITextField *nameTextField; 
UITextField *passTextField; 

然後使用這些在實施中引用。

1

將用於創建UITextField的變量存儲爲標頭中的實例變量 - 或更好的@property - 而不是局部變量。因此,您可以從班級中的任何地方訪問它們。

.H:

@interface YourClass : UIViewController { 

} 
@property(nonatomic, retain) IBOutlet UITextField* nameField; 
@property(nonatomic, retain) IBOutlet UITextField* passField; 
@end 

.M:

@implementation YourClass 
@synthesize nameField, passField; 
-(void)dealloc { 
    self.nameField = nil; // release memory when your class is deallocated 
    self.passField = nil; // release memory when your class is deallocated 
    [super dealloc]; 
} 

-(void)loadView { 
    // here create your UITextFields programatically... 
    self.nameField = [[[UITextField alloc] initWitHFrame:...] autorelease]; 
    ... 
    self.passField = [[[UITextField alloc] initWitHFrame:...] autorelease]; 
    ... 

    // or much more easier, you should create them using InterfaceBuilder, 
    // this would save you a lot of code 
} 

-(IBAction)login { 
    NSLog(@"name: %@ ; pass: %@", nameField.text, passField.text); 
} 
@end 

僅供參考,請注意,如果使用InterfaceBuilder中建立自己的界面,你會不會有問題,你會已經有IBOutlets連接到您的UITextFields(並且您將保存通過代碼創建和配置您的UITextField所需的所有代碼)。


邊注:請不要使用NSLog(stringVariable);而是NSLog(@"%@",stringVariable);因爲如果你的stringVariable包含litteral「%」後跟任何說明符字符(例如,你的情況,如果您的名稱字段中輸入的文本,並且由用戶輸入,包含「user%xyz」),你的代碼將會崩潰。所以總是使用一個靜態輸入的字符串作爲NSLog的第一個參數,而不是一個變量。

0

UIView對象有一個NSInteger 標記在動態創建視圖的情況下可能有用的屬性。在創建時設置該值,並使用viewWithTag:從其任何父視圖中查看。

相關問題