網頁

2012年4月11日 星期三

iOS學習_Login input using UIAlertView

登入頁面可以說是系統開發的常客,裡面的認證機制是一回事,但在行動化裝置開發時,就連界面的排版也變的需要特別考慮一下,原因是鍵盤現在不在桌上,而是螢幕上。

假設我們做了一個曠世巨作叫做『Fighting 阿蠻』,而且這是一個需要登入的遊戲,所以我們精心設計了超有氣勢的登入畫面,就像平常在寫Web的程式一樣:

但當按下輸入框時就會發現一個很大的問題:

因為虛擬鍵盤的關係,使用者看不見輸入的內容,這時候大致上有三個選擇:
1. 不管他,反正鍵盤收起來就可以看到了。
2. 把輸入框設計在鍵盤檔不到的地方。
3. 利用UIAlertView或UIPopover的特性,當鍵盤出現時會自動作位置上的調整。

那本篇就是要介紹怎麼用UIAlertView來完成這件事情。
-----------------------------------------

在5.0以前的時代,UIAlertView預設模式下並沒有辦法出現兩個輸入框,如果要做到就必須要自己客制化一個AlertView,但到了5.0以後,Apple幫我們加入了這個模式,所以要達成類似的要求變得非常簡單:

-(void)btn_login_click:(id)sender
{
UIAlertView *loginalertview = [[UIAlertView alloc] initWithTitle:@"系統登入"
message:nil
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"登入", nil ];
loginalertview.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
loginalertview.tag = 1;
[loginalertview show];
[loginalertview release];
}

與使用一般的UIAlertView一樣,只需要增加alertViewStyle的設定,就可以達到下面的效果。

但是輸入框內的提示卻是Login與Password,有時候我們可能希望提示的內容是自己想要的文字,就可以藉由willPresentAlertView在顯示前更改。

-(void)willPresentAlertView:(UIAlertView *)alertView
{
if(alertView.tag==1)
{
UITextField *accoutName=[alertView textFieldAtIndex:0];
UITextField *accoutPassword=[alertView textFieldAtIndex:1];
accoutName.placeholder= @"勇士名稱";
accoutPassword.placeholder= @"傳送金鑰";
}
}

效果:

最後,我們只需要去處理當按下『登入』按鈕後,取得使用者輸入的帳號跟密碼,再進行需要執行的動作。

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag==1 && buttonIndex ==1)
{
UITextField *accoutName=[alertView textFieldAtIndex:0];
UITextField *accoutPassword=[alertView textFieldAtIndex:1];
NSLog(@"accoutName:%@",accoutName.text);
NSLog(@"accoutPassword:%@",accoutPassword.text);
[self CheckLoginUser:accoutName.text password:accoutPassword.text]
}
}

沒有留言:

張貼留言