续上次谈论键盘遮挡解决方案问题, 上次请见http://blog.csdn.net/dexin5195/article/details/38690431
这次对于第二种情况的解决方案, 就是不考虑移动控件位置, 而是将输入的textField.text直接显示在加在键盘上方的Toolbar上:
实现原理及步骤:
1. 自定义textField, 重绘inputAccessoryView, 其中加入toolbar, done按钮, 和label(用于显示textField的内容);
PS:done按钮是UIBarButtonItem类型, 可以通过array方式加入toolbar中, 但是label需要通过addsubview方式加入(当然你说done用UIButton, 然后用addsubview加入也是可以的);
2. 初始化方法中加入UITextFieldTextDidChangeNotification的监听, 并在监听处理的方法中改变label.text = self.text, 这样就可以了, 这里需要注意的是加入监听后销毁的时候必须取消监听;
3. 代码如下:
// ToolbarTextField.m
// yuyueba
//
// Created by APPLE on 14-8-18.
// Copyright (coffee) 2014年 Michael Cheng. All rights reserved.
//
#import "ToolbarTextField.h"
@implementation ToolbarTextField{
UILabel *label;
UIToolbar *inputAccessoryView;
}
@synthesize label;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
return self;
}
- (id) initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
return self;
}
- (void)textFieldTextDidChange:(NSNotification *)notification
{
if (label) {
label.text = self.text;
}
}
#pragma mark - inputAccessoryView with toolbar
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)done:(id)sender {
[self resignFirstResponder];
[super resignFirstResponder];
}
- (UIView *)inputAccessoryView {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return nil;
} else {
if (!inputAccessoryView) {
inputAccessoryView = [[UIToolbar alloc] init];
inputAccessoryView.barStyle = UIBarStyleBlackTranslucent;
inputAccessoryView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[inputAccessoryView sizeToFit];
CGRect frame = inputAccessoryView.frame;
frame.size.height = 30.0f;
inputAccessoryView.frame = frame;
/* add displayView */
if (!label) {
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
[label setTextColor:[UIColor whiteColor]];
[inputAccessoryView addSubview:label];
}
UIBarButtonItem *doneBtn =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *array = [NSArray arrayWithObjects: flexibleSpaceLeft, doneBtn, nil];
[inputAccessoryView setItems:array];
}
return inputAccessoryView;
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end