是否可以将inputAccessoryView用于实际输入
问题描述:
今天上午,我正在查看一些我在某处(并在应用程序中使用)找到的旧代码,该代码为了从用户那里获取一个输入字符串,需要一个UIAlertView
。对于这个目的来说这太过分了,看起来很傻,但我从来没有见过更简单的方法。然后我想出了以下办法,其中似乎工作(iPad 5.1.1和模拟器)。是否可以将inputAccessoryView用于实际输入
我的问题有点不确定,但实际上,在这种情况下,这种情况可以作为一种策略:创建带有附件视图的屏幕外文本字段,在附件视图中放置代理文本字段,以及将各种属性设置转发给代理?
PMKeyboardTextField.h:
#import <UIKit/UIKit.h>
@interface PMKeyboardTextField : UITextField
- (id)initWithPrompt:(NSString *)prompt;
@end
PMKeyboardTextField.m:
#import "PMKeyboardTextField.h"
@interface PMKeyboardTextField()
@property (nonatomic, strong) UITextField *inputField;
@end
@implementation PMKeyboardTextField
@synthesize inputField = _inputField;
- (id)initWithPrompt:(NSString *)prompt {
self = [super initWithFrame:CGRectMake(-1, -1, 1, 1)];
if (self) {
UIView *accessory = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 72)];
[accessory setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.8]];
UILabel *getLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, 284, 21)];
[getLabel setBackgroundColor:[UIColor clearColor]];
getLabel.text = prompt;
[accessory addSubview:getLabel];
self.inputField = [[UITextField alloc] initWithFrame:CGRectMake(18, 37, 264, 31)];
[accessory addSubview:self.inputField];
self.inputAccessoryView = accessory;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow)
name:UIKeyboardDidShowNotification
object:nil];
}
return self;
}
- (void)keyboardDidShow {
[self.inputField becomeFirstResponder];
}
- (id<UITextFieldDelegate>)delegate {
return self.inputField.delegate;
}
- (void)setDelegate:(id<UITextFieldDelegate>)delegate {
self.inputField.delegate = delegate;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
答
尽管我喜欢这个想法,因为它能够避免警报视图的过度混乱或需要重新定位屏幕视图,但在另一个论坛中指出了致命缺陷:有些人使用外部键盘!
答
如果你的目标的iOS 5.0或更高版本,则不需要破解警报视图中添加一个文本字段。您只需将警报视图的alertViewStyle
设置为UIAlertViewStylePlainTextInput
即可为警报视图指定一个明文输入字段,然后您可以通过将textFieldAtIndex:
发送到警报视图来访问该明文输入字段。
除此之外,您的解决方法似乎没问题。我想你必须添加你的屏幕外的文本字段到警报视图的窗口,而不是你的普通应用程序窗口。
实际上,这是为了在不创建警报视图的情况下在任何视图中工作。 (我想到的实际用途是当有人点击'+'将某些东西添加到表视图中时,我希望它们在创建时将其命名为不将可编辑字段放入表视图单元格中。 。或者提出那个不必要的警报视图)。 – 2012-08-15 17:26:01
在这种情况下,我只需在顶层视图的底部边缘添加辅助栏作为常规子视图,将'becomeFirstResponder'发送到其中的文本框,然后滑动它基于'UIKeyboardWillShowNotification'。 – 2012-08-15 17:32:56