iPhone开发——点击UIImageView弹出键盘

Home / iOS MrLee 2015-6-4 3410

同样的需求,做Android客户端时在没有文本框时也可以通过inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);调出系统键盘。
但是,IOS中貌似没有这样的接口,所以可以采用“隐藏文本框”的方式,调出系统键盘,具体实现如下:
1、在ViewController.xib上放置一个ImageView和一个UITextField(代码中将其设置为隐藏),如下:


2、ViewController.h如下:
//  ViewController.h  
//  showKeyBoard  
//  
//  Created by Zhang Yanguang on 12-11-27.  
//  Copyright (c) 2012年 MyCompanyName. All rights reserved.  
//  
  
#import   
  
@interface ViewController : UIViewController{  
    BOOL hasOpenKeyBoard;//是否打开键盘  
}  
  
@property(strong,nonatomic)IBOutlet UIImageView *imgView;  
@property(strong,nonatomic)IBOutlet UITextField *textField;  
  
-(IBAction)showKeyBoard:(id)sender;  
@end  
3、ViewController.m如下:
//  ViewController.m  
//  showKeyBoard  
//  
//  Created by Zhang Yanguang on 12-11-27.  
//  Copyright (c) 2012年 MyCompanyName. All rights reserved.  
//  
  
#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、效果如下:

本文链接:https://www.it72.com/3117.htm

推荐阅读
最新回复 (0)
返回