iPhone开发实现点击一个UIImageView时打开键盘 .

同样的需求,做Android客户端时在没有文本框时也可以通过inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);调出系统键盘。

但是,IOS中貌似没有这样的接口,所以可以采用“隐藏文本框”的方式,调出系统键盘,具体实现如下:


1、在ViewController.xib上放置一个ImageView和一个UITextField(代码中将其设置为隐藏),如下:

[img]
[img]http://dl.iteye.com/upload/attachment/0078/7385/9a396a04-af2c-3afd-b7fc-6997d443338d.png[/img]
[/img]


2、ViewController.h如下:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>{
BOOL hasOpenKeyBoard;//是否打开键盘
}

@property(strong,nonatomic)IBOutlet UIImageView *imgView;
@property(strong,nonatomic)IBOutlet UITextField *textField;

-(IBAction)showKeyBoard:(id)sender;
@end



3、ViewController.m如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize imgView;
@synthesize textField;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//隐藏文本框
textField.hidden = YES;
//设置代理
textField.delegate = self;
hasOpenKeyBoard = false;
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesBegan...");
//[imgView becomeFirstResponder];
if(!hasOpenKeyBoard){
[textField becomeFirstResponder];
}else{
[textField resignFirstResponder];
}
hasOpenKeyBoard=!hasOpenKeyBoard;
}

#pragma mark UITextFieldDelegate Methods
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"string=%@",string);
return YES;
}

@end

方法shouldChangeCharactersInRange中可以监听到键盘输入。


4、效果如下:
[img]
[img]http://dl.iteye.com/upload/attachment/0078/7387/c149a3cf-540a-383c-95ed-1cefcde541d7.png[/img]
[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值