Keyboard processing example

Source: Internet
Author: User

Keyboard processing example
Keyboard processing exampleStep 1: Build a simple interface

Step 2. Customize XIB to describe gender
+ (Id) sexBox
{
Return [[NSBundle mainBundle] loadNibNamed: @ "MJSexBox" owner: niloptions: nil] [0];
}

2.1 click "Listen to gender" and modify the status of the button.
# Pragma mark changed gender selection
-(IBAction) sexChange {
If (_ manBtn. enabled) {// click male
_ ManBtn. enabled = NO;
_ WomanBtn. enabled = YES;
} Else {// click female
_ ManBtn. enabled = YES;
_ WomanBtn. enabled = NO;
}
}
2. Add a gender selection control to the Controller
MJSexBox * sexBox = [MJSexBox sexBox];
SexBox. center = CGPointMake (150, 70 );
[Self. view addSubview: sexBox];
Step 3: Customize the keyboard
3. 1. Set the birthday keyboard
// 1. 1. Birthday
UIDatePicker * datePicker = [[UIDatePicker alloc] init];
DatePicker. datePickerMode = UIDatePickerModeDate; // only display date 5
DatePicker. locale = [[NSLocale alloc] initWithLocaleIdentifier: @ "zh_CN"];
[DatePicker addTarget: selfaction: @ selector (birthdayChange :) forControlEvents: UIControlEventValueChanged];
_ BirthdayField. inputView = datePicker; // you can specify the keyboard as the date Selection control.
_ BirthdayField. delegate = self;


3.2 do not input text on the birthday keyboard
# Pragma mark-UITextField proxy
# Pragma mark this method is called every time a user inputs a text. NO is returned and NO input is allowed.
-(BOOL) textField :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string
{
Return NO;
}

3.3 listen to the birthday keyboard value change event
# Pragma mark-birthday change
-(Void) birthdayChange :( UIDatePicker *) picker
{
// 1. Get the current time
NSDateFormatter * fmt = [[NSDateFormatter alloc] init];
Fmt. dateFormat = @ "yyyy-MM-dd ";
NSString * time = [fmt stringFromDate: picker. date];

// 2. assign a value to the text box
_ BirthdayField. text = time;
}

Step 4. Set up a city
4.1 Use xib to describe the city keyboard, set UIPickerView proxy and data source, and create a custom view.
+ (Id) cityPicker
{
Return [[NSBundle mainBundle] loadNibNamed: @ "MJCityPicker" owner: niloptions: nil] [0];
}
4.2 load data, called in awakeFromNib
# Pragma mark is called once when any object is created from xib
-(Void) awakeFromNib
{
NSArray * array = [NSArray arrayWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @ "cities. plist" ofType: nil];

_ Provinces = [NSMutableArray array];
For (NSDictionary * dictin array ){
MJProvince * p = [MJProvince provinceWithDict: dict];
[_ Provinces addObject: p];
}
}
4.3 implement data source and proxy methods.

# Pragma mark-UIPickerView Data Source Method
-(NSInteger) numberOfComponentsInPickerView :( UIPickerView *) pickerView
{
Return 2;
}

# Number of rows of data in the component column of The pragma mark
-(NSInteger) pickerView :( UIPickerView *) pickerView numberOfRowsInComponent :( NSInteger) component
{
If (component = 0) {// number of provinces
Return _ provinces. count;
} Else {// number of rows (number of cities) of the selected Province)
// 1. Obtain the province selected
Int pIndex = [pickerView selectedRowInComponent: 0];

// 2. Retrieve the province Model
MJProvince * p = _ provinces [pIndex];

// 3. Return the number of cities in the current Province
Return p. cities. count;
}
}

# Pragma mark-UIPickerView proxy method
-(NSString *) pickerView :( UIPickerView *) pickerView titleForRow :( NSInteger) row forComponent :( NSInteger) component
{
If (component = 0) {// display the province
// 1. Retrieve the province Model
MJProvince * p = _ provinces [row];

// 2. Retrieve the province name
Return p. name;
} Else {// which city is displayed
// 1. Obtain the province selected
Int pIndex = [pickerView selectedRowInComponent: 0];

// 2. Retrieve the province Model
MJProvince * p = _ provinces [pIndex];

// 3. Return the city name of the corresponding row
Return p. cities [row];
}
}

# The pragma mark listener selects a row in a column
-(Void) pickerView :( UIPickerView *) pickerView didSelectRow :( NSInteger) row inComponent :( NSInteger) component
{
If (component = 0) {// changed the province
// Refresh 1st columns of data (refresh the data and call the corresponding method of data source and proxy to obtain the data)
[PickerView reloadComponent: 1];

// Select the 1st rows in the 0th Column
[PickerView selectRow: 0 inComponent: 1 animated: YES];
}

// Modify text
// 1. Obtain the name of the selected Province
Int pIndex = [pickerView selectedRowInComponent: 0];
MJProvince * p = _ provinces [pIndex];

// 2. Obtain the selected city location
Int cIndex = [pickerView selectedRowInComponent: 1];

// 3. Notification proxy
If ([_ delegate respondsToSelector: @ selector (cityPicker: citySelectWithProvince: city :)]) {
[_ Delegate cityPicker: selfcitySelectWithProvince: p. name city: p. cities [cIndex];
}
}

4.4 call the custom view to set the city keyboard
Set City
MJCityPicker * cityPicker = [MJCityPicker cityPicker];
CityPicker. delegate = self;
_ CityField. inputView = cityPicker; // set the keyboard to pickerview.
_ CityField. delegate = self;

# Pragma mark-MJCityPicker proxy method
# Pragma mark is called when a city is selected
-(Void) cityPicker :( MJCityPicker *) cityPicker citySelectWithProvince :( NSString *) province city :( NSString *) city
{
_ CityField. text = [NSString stringWithFormat: @ "% @%@", province, city];
}

4.5 declare a protocol for the custom city keyboard and add a proxy attribute to notify the proxy to do something when scrolling the keyboard.

@ ProtocolMJCityPickerDelegate

@ Optional
-(Void) cityPicker :( MJCityPicker *) cityPicker citySelectWithProvince :( NSString *) province city :( NSString *) city;

@ End

4.6 method of implementing modern protocol in the controller.
# Pragma mark-MJCityPicker proxy method
# Pragma mark is called when a city is selected
-(Void) cityPicker :( MJCityPicker *) cityPicker citySelectWithProvince :( NSString *) province city :( NSString *) city
{
_ CityField. text = [NSString stringWithFormat: @ "% @%@", province, city];
}
Step 5: tool bar
5.1 customize an xib description Toolbar
+ (Id) keyboardTool
{
Return [[NSBundle mainBundle] loadNibNamed: @ "MJKeyboardTool" owner: niloptions: nil] [0];
}

5.2 wrap the toolbar with a view to prevent the outside world from modifying the toolbar. Because the outside world obtains the UIView rather than the toolbar, the attributes in the toolbar cannot be directly obtained.
5.3 define a custom toolbar class and bind it with xib.
-(IBAction) previous; // previous
-(IBAction) next; // next
-(IBAction) done; // complete

5.4 define a protocol and notify the proxy to click the event
@ Optional
-(Void) keyboardTool :( MJKeyboardTool *) keyboardTool itemClick :( MJKeyboardToolItemType) itemType;
@ End

5.5 define an enumeration type and differentiate buttons
Typedefenum {
MJKeyboardToolItemTypePrevious, // previous
MJKeyboardToolItemTypeNext, // next
MJKeyboardToolItemTypeDone // complete
} MJKeyboardToolItemType;

5.6 notify the proxy when you click the button

# Previous pragma mark
-(Void) previous
{
// Notification proxy (the previous button is clicked)
If ([_ delegate respondsToSelector: @ selector (keyboardTool: itemClick :)]) {
[_ Delegate keyboardTool: selfitemClick: MJKeyboardToolItemTypePrevious];
}
}

# Pragma mark next
-(Void) next
{
// Notification proxy (the next button is clicked)
If ([_ delegate respondsToSelector: @ selector (keyboardTool: itemClick :)]) {
[_ Delegate keyboardTool: selfitemClick: MJKeyboardToolItemTypeNext];
}
}

# Pragma mark completed
-(Void) done
{
// Notification proxy (the completion button is clicked)
If ([_ delegate respondsToSelector: @ selector (keyboardTool: itemClick :)]) {
[_ Delegate keyboardTool: selfitemClick: MJKeyboardToolItemTypeDone];
}
}

5.7 let the Controller act as the proxy for the toolbar and implement the toolbar proxy method

# Pragma mark-MJKeyboardTool proxy method
# Pragma mark will be called when the button above the toolbar is clicked
-(Void) keyboardTool :( SUNKeyboardTool *) keyboardTool itemClick :( SUNKeyboardToolItemType) itemType
{
If (itemType = doneKeyboardToolItemType ){
[Self. viewendEditing: YES];
} Else {
Int index = [_ fieldsindexOfObject: _ focusedField];
If (itemType = previuskeyboardtoolitemtype ){
Index --;
} Else {
Index ++;
}
// Become the first responder
[_ Fields [index] becomeFirstResponder];
}
}

5.8 listen to start editing of all text boxes and set the proxy of all text boxes as the Controller
// 3. Obtain all text input boxes
MJKeyboardTool * tool = [MJKeyboardTool keyboardTool];
Tool. delegate = self;
For (UIView * child in self. view. subviews ){
// If it is a text input box, set the toolbar
If ([child isKindOfClass: [UITextField class]) {
UITextField * field = (UITextField *) child;
Field. inputAccessoryView = tool;
}
}


5.9 determine whether the button on the toolbar can be clicked
# Pragma mark-UITextField proxy
# Pragma mark-called when you start to click the text box
-(Void) textFieldDidBeginEditing :( UITextField *) textField
{
_ FocusedField = textField;
Int index = [_ fieldsindexOfObject: _ focusedField];
_ KeyboardTool. previusbtm. enabled = (index! = 0 );
_ KeyboardTool. nextBtm. enabled = (index! = (_ Fields. count-1 ));
}



5.10 The listening system sends a keyboard scroll notification.
# Pragma mark-notification from the listening system
-(Void) addkeyboard
{
Nsicationicationcenter * center = [nsnotificationcenterdefacenter];

// Listen to the keyboard to display
[Center addObserver: selfselector: @ selector (showKeyboard :) name: UIKeyboardWillShowNotificationobject: nil];

// Listen to the keyboard to hide
[Center addObserver: selfselector: @ selector (keyboardWillHide :) name: uikeyboardwillhidenotifobject: nil];
}

5.11 move the view up when the keyboard blocks the text box
# Pragma mark-the listening Keyboard will be displayed
-(Void) showKeyboard :( NSNotification *) noti
{
NSLog (@ "% @", noti. userInfo );
// 1. Obtain the Y value at the bottom of the current focus text box
CGFloat Y = CGRectGetMaxY (_ focusedField. frame );
NSLog (@ "% f", Y );
// 2. Retrieve the keyboard height (Controller height-keyboard height)
CGFloat keyboardH = [noti. userInfo [UIKeyboardFrameBeginUserInfoKey] CGRectValue]. size. height;
CGFloat keyboardY = self. view. frame. size. height-keyboardH;
// 3. Compare the text box size
CGFloat duration = [noti. userInfo [UIKeyboardAnimationDurationUserInfoKey] floatValue];

[UIViewanimateWithDuration: durationanimations: ^ {
// The keyboard hides the text box.
If (keyboardY <Y ){
Self. view. transform = CGAffineTransformMakeTranslation (0, keyboardY-Y-10 );
} Else {
Self. view. transform = CGAffineTransformIdentity;
}
}];

}

# Pragma mark-the listening Keyboard will be hidden
-(Void) keyboardWillHide :( NSNotification *) noti
{
// Duration
CGFloat duration = [noti. userInfo [UIKeyboardAnimationDurationUserInfoKey] floatValue];

// Set the animation to hide the keyboard according to the duration.
[UIViewanimateWithDuration: durationanimations: ^ {
// The CGAffineTransformIdentity attribute can be restored to the State before the animation.
Self. view. transform = CGAffineTransformIdentity;
}];
}

5.12 listener removal notification
# Pragma mark-cancel registration before the listener is destroyed
-(Void) dealloc
{
[[Nsnotificationcenterdefacenter] removeObserver: self];
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.