如何在iOS中以编程方式更改UIKeyBoard的框架

时间:2012-05-04 07:12:47

标签: iphone ios ipad uikeyboard

嗯,在发布这个问题之前,我已经经历了一些不错的护目镜,但却未能找到正确的答案。 我无法在这里解释我的整个应用场景,因为解释起来有点复杂。所以,让我非常简单地提出这个问题。如何更改 UIKeyBoard .i.e的框架。我希望 UIKeyBoard旋转或向上翻转90度以支持我的视图位置。 我有出路吗?

1 个答案:

答案 0 :(得分:4)

您无法更改默认键盘。但是,您可以通过将其设置为inputView(例如,UITextField)来创建自定义UIView以用作键盘替换。

虽然创建自定义键盘需要一些时间,但它适用于较旧的iOS版本(UITextField上的inputView在iOS 3.2及更高版本中可用)并且支持物理键盘(键盘会自动隐藏,如果有的话连接)。

以下是创建垂直键盘的示例代码:

<强>接口

#import <UIKit/UIKit.h>

@interface CustomKeyboardView : UIView

@property (nonatomic, strong) UIView *innerInputView;
@property (nonatomic, strong) UIView *underlayingView;

- (id)initForUnderlayingView:(UIView*)underlayingView;

@end

<强>实施

#import "CustomKeyboardView.h"

@implementation CustomKeyboardView

@synthesize innerInputView=_innerInputView;
@synthesize underlayingView=_underlayingView;

- (id)initForUnderlayingView:(UIView*)underlayingView
{
    //  Init a CustomKeyboardView with the size of the underlying view
    //  You might want to set an autoresizingMask on the innerInputView.
    self = [super initWithFrame:underlayingView.bounds];
    if (self) 
    {
        self.underlayingView = underlayingView;

        //  Create the UIView that will contain the actual keyboard
        self.innerInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, underlayingView.bounds.size.height)];

        //  You would need to add your custom buttons to this view; for this example, it's just red
        self.innerInputView.backgroundColor = [UIColor redColor];

        [self addSubview:self.innerInputView];
    }
    return self;
}

-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event 
{
    //  A hitTest is executed whenever the user touches this UIView or any of its subviews.

    id hitTest = [super hitTest:point withEvent:event];

    //  Since we want to ignore any clicks on the "transparent" part (this view), we execute another hitTest on the underlying view.
    if (hitTest == self)
    {
        return [self.underlayingView hitTest:point withEvent:nil];
    }

    return hitTest;
}

@end

在某些UIViewController中使用自定义键盘:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CustomKeyboardView *customKeyboard = [[CustomKeyboardView alloc] initForUnderlayingView:self.view];
    textField.inputView = customKeyboard;
}