iOS–inputView和inputAccessoryView
什么是inputView和inputAccessoryView?
如果是UITextField和UITextView,下面是声明文件源代码:
// set while first responder, will not take effect until reloadInputViews is called.
@property (readwrite, retain) UIView *inputView;
@property (readwrite, retain) UIView *inputAccessoryView;
如果是其他的控件,继承了UIResponder,(UIView 是UIResponder的子类),下面是声明文件源代码:
// Called and presented when object becomes first responder. Goes up the responder chain.
@property (nonatomic, readonly, retain) UIView *inputView NS_AVAILABLE_IOS(3_2);
@property (nonatomic, readonly, retain) UIView *inputAccessoryView NS_AVAILABLE_IOS(3_2);
自定义TextField或TextView
自定义只需要重写下面的两个属性
textField.inputView = [UIView alloc] init];
textField.inputAccessoryView = [UIToolbar alloc] init];
自定义继承了UIResponder类的控件
需要自定义UIResponder的子类,我们需要在重新定义一个子类,然后再这个子类中声明inputView
,inputAccessoryView
为可读可写属性。然后重写getter方法。同时还需要覆盖-(BOOL)canBecomeFirstResponder
方法。
下面以UIButton为例子的子类重设代码:
#import <UIKit/UIKit.h>
@interface ABEButton : UIButton
@property (nonatomic, strong)UIToolbar *inputAccessoryView;
@property (nonatomic, strong)UIView *inputView;
@end
#import "ABEButton.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
@implementation ABEButton
-(BOOL)canBecomeFirstResponder
{
return YES;
}
#pragma mark- Getter, Setter
- (UIView*)inputView{
if (!_inputView) {
_inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 220)];
_inputView.backgroundColor = [UIColor redColor];
}
return _inputView;
}
- (UIToolbar*)inputAccessoryView{
if (!_inputAccessoryView) {
_inputAccessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
_inputAccessoryView.backgroundColor = [UIColor grayColor];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"隐藏" style:UIBarButtonItemStylePlain target:self action:@selector(clickFinishButton:)];
_inputAccessoryView.items = @[item];
}
return _inputAccessoryView;
}
#pragma mark- Private method
- (void)clickFinishButton:(ABEButton*)buttonItem{
[self resignFirstResponder];
}
@end
这样,我们就可以使用点击button,弹出inputView了。