iOS組件之UITextField

來源:互聯網
上載者:User

1.建立
01.UITextField* myTextField = [[UITextField alloc]initWithFrame:CGRectMake(50, 100, 200, 50)];  

2.設定委託
01.myTextField.delegate = self;//委託類需要遵守UITextFieldDelegate協議  

3.設定屬性UIControl屬性對UITextField完全可以用,下面的都是UITextField擴充的屬性
01.myTextField.textAlignment = UITextAlignmentLeft;//預設就是靠左對齊,這個是UITextField擴充屬性  
 
02.myTextField.borderStyle = UITextBorderStyleBezel;//預設是沒有邊框,如果使用了自訂的背景圖片邊框會被忽略掉  
 
03.myTextField.placeholder = @"請在此輸入帳號";//為空白文字欄位繪製一個灰色字串作為預留位置  
 
04.myTextField.clearsOnBeginEditing = YES;//設定為YES當用點觸文字欄位時,欄位內容會被清除  
 
05.myTextField.adjustsFontSizeToFitWidth = YES;//設定為YES時文本會自動縮小以適應文字視窗大小。預設是保持原來大小,而讓長文本滾動  
 
06.//myTextField.background = [UIImage imageNamed:@"registBtn"];//可以接受UIImage對象,此項設定則邊框失效。  
 
07.myTextField.clearButtonMode = UITextFieldViewModeUnlessEditing;//右邊顯示的'X'清楚按鈕  
 
08.//myTextField.LeftView =  
 
09.//myTextField.leftViewMode =   
 
10.//myTextField.RightView =  
 
11.//myTextField.rightViewMode =    

4.下列方法在建立一個UITextField的子類時可以重寫:borderRectForBounds指定矩形邊界textRectForBounds 指定顯示文本的邊界placeholderRectForBounds指定站位文本的邊界editingRectForBounds指定編輯中文本的邊界clearButtonRectForBounds指定顯示清除按鈕的邊界leftViewRectForBounds指定顯示左附著視圖的邊界rightViewRectForBounds指定顯示右附著視圖的邊界委託方法。
========================================
01.- (CGRect)clearButtonForBounds:(CGRect)bounds{  
 
02.    return CGRectMake(bounds.origin.x +bounds.size.width-50,   
 
03.                      bounds.origin.y+bounds.size.height-20, 16, 16);  
 
04.}  
========================================

01.- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{  
 
02.    //返回一個BOOL值,指定是否循序文字欄位開始編輯  
 
03.    return YES;  
 
04.}  

========================================
01.- (void)textFieldDidBeginEditing:(UITextField *)textField{  
 
02.    //開始編輯時觸發,文字欄位將成為first responder  
 
03.}  

========================================
01.- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{  
 
02.    //返回BOOL值,指定是否允許文字欄位結束編輯,當編輯結束,文字欄位會讓出first responder  
 
03.    //要想在使用者結束編輯時阻止文字欄位消失,可以返回NO  
 
04.    //這對一些文字欄位必須始終保持活躍狀態的程式很有用,比如立即訊息  
 
05.    return NO;  
 
06.}  

========================================
01.- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{  
 
02.    //當使用者使用自動校正功能,把輸入的文字修改為推薦的文字時,就會調用這個方法。  
 
03.    //這對於想要加入撤銷選項的應用程式特別有用  
 
04.    //可以跟蹤欄位內所做的最後一次修改,也可以對所有編輯做日誌記錄,用作審計用途。     
 
05.    //要防止文字被改變可以返回NO  
 
06.    //這個方法的參數中有一個NSRange對象,指明了被改變文字的位置,建議修改的文本也在其中  
 
07.    return YES;  
 
08.}  

========================================
01.- (BOOL)textFieldShouldClear:(UITextField *)textField{  
 
02.    //返回一個BOOL值指明是否允許根據使用者請求清除內容  
 
03.    //可以設定在特定條件下才允許清除內容  
 
04.    return YES;  
 
05.}  

========================================
01.-(BOOL)textFieldShouldReturn:(UITextField *)textField{  
 
02.    //返回一個BOOL值,指明是否允許在按下斷行符號鍵時結束編輯  
 
03.    //如果允許要調用resignFirstResponder 方法,這回導致結束編輯,而鍵盤會被收合  
 
04.    [textField resignFirstResponder];//查一下resign這個單詞的意思就明白這個方法了  
 
05.    return YES;  
 
06.}  

========================================
虛擬鍵盤擋住UITextField時的解決方案:
RootViewController.h 中:
#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController<UITextFieldDelegate> {

UITextField *textField1;
UITextField *textField2;

}
@property (nonatomic,retain) UITextField *textField1;
@property (nonatomic ,retain) UITextField *textField2;

-(IBAction)backgroundTap:(id)sender;

@end
RootViewController.m 中:
#import "RootViewController.h"

@implementation RootViewController
@synthesize textField1;
@synthesize textField2;

// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {

UIView *back = [[UIView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
back.backgroundColor = [UIColor grayColor];
self.view = back;
[back release];
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];

UIControl *_back = [[UIControl alloc] initWithFrame:self.view.frame];
_back.backgroundColor = [UIColor grayColor];
self.view = _back;
[_back release];
[(UIControl *)self.view addTarget:self action:@selector(backgroundTap:) forControlEvents:UIControlEventTouchDown];

textField1 = [[UITextField alloc] initWithFrame:CGRectMake(20, 300, 200, 30)];
textField1.backgroundColor = [UIColor clearColor];
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.textColor = [UIColor redColor];
textField1.delegate = self;
[self.view addSubview:textField1];

textField2 = [[UITextField alloc] initWithFrame:CGRectMake(20, 30, 200, 30)];
textField2.backgroundColor = [UIColor clearColor];
textField2.borderStyle = UITextBorderStyleRoundedRect;
textField2.textColor = [UIColor redColor];
textField2.delegate = self;
[self.view addSubview:textField2];
}

#pragma mark -
#pragma mark 解決虛擬鍵盤擋住UITextField的方法
- (void)keyboardWillShow:(NSNotification *)noti

//鍵盤輸入的介面調整 
//鍵盤的高度
float height = 216.0; 
CGRect frame = self.view.frame; 
frame.size = CGSizeMake(frame.size.width, frame.size.height - height); 
[UIView beginAnimations:@"Curl"context:nil];//動畫開始 
[UIView setAnimationDuration:0.30]; 
[UIView setAnimationDelegate:self]; 
[self.view setFrame:frame]; 
[UIView commitAnimations];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField

// When the user presses return, take focus away from the text field so that the keyboard is dismissed. 
NSTimeInterval animationDuration = 0.30f; 
[UIView beginAnimations:@"ResizeForKeyboard" context:nil]; 
[UIView setAnimationDuration:animationDuration]; 
CGRect rect = CGRectMake(0.0f, 20.0f, self.view.frame.size.width, self.view.frame.size.height); 
self.view.frame = rect;
[UIView commitAnimations];
[textField resignFirstResponder];
return YES; 
}

- (void)textFieldDidBeginEditing:(UITextField *)textField

CGRect frame = textField.frame;
int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//鍵盤高度216
NSTimeInterval animationDuration = 0.30f; 
[UIView beginAnimations:@"ResizeForKeyBoard" context:nil]; 
[UIView setAnimationDuration:animationDuration];
float width = self.view.frame.size.width; 
float height = self.view.frame.size.height; 
if(offset > 0)
{
CGRect rect = CGRectMake(0.0f, -offset,width,height); 
self.view.frame = rect; 

[UIView commitAnimations]; 
}

#pragma mark -
#pragma mark 觸摸背景來關閉虛擬鍵盤
-(IBAction)backgroundTap:(id)sender
{
// When the user presses return, take focus away from the text field so that the keyboard is dismissed. 
NSTimeInterval animationDuration = 0.30f; 
[UIView beginAnimations:@"ResizeForKeyboard" context:nil]; 
[UIView setAnimationDuration:animationDuration]; 
CGRect rect = CGRectMake(0.0f, 20.0f, self.view.frame.size.width, self.view.frame.size.height); 
self.view.frame = rect;
[UIView commitAnimations];

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];
}

#pragma mark -

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc {
[textField1 release];
[textField2 release];
[super dealloc];
}
RootViewController.m 中的backgroundTap:方法,用來實現觸摸背景來關閉虛擬鍵盤。
這個方法用的時候首先把RootViewController上的view改成UIControl,然後通過UIControl的事件UIControlEventTouchDown來觸發上面的方法backgroundTap: 。
注意下面的代碼:
UIControl *_back = [[UIControl alloc] initWithFrame:self.view.frame];
_back.backgroundColor = [UIColor grayColor];
self.view = _back;
[_back release];
[(UIControl *)self.view addTarget:self action:@selector(backgroundTap:) forControlEvents:UIControlEventTouchDown];

解決textField被鍵盤擋住的問題的方法有三個:
- (void)keyboardWillShow:(NSNotification *)noti;//調整虛擬鍵盤與self.view之間的關係。
-(BOOL)textFieldShouldReturn:(UITextField *)textField;//觸控式鍵盤上的return鍵時關閉虛擬鍵盤
- (void)textFieldDidBeginEditing:(UITextField *)textField;//當編輯文本的時候,如果虛擬鍵盤擋住了textField,整個view就會向上移動。移動範圍是一個鍵盤的高度216。

參考文章:
(1) http://bbs.chinaunix.net/thread-3679125-1-1.html
(2) http://yang152412.blog.163.com/blog/static/1758615822012284143183/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.