iPhone 自定义键盘按键

本文介绍如何在iOS应用中为键盘添加自定义按钮,并通过监听键盘显示和隐藏的通知来实现功能。具体步骤包括注册键盘通知、创建自定义按钮并设置样式、定位键盘视图以及将按钮添加到键盘上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先注册消息通知UIKeyboardWillShowNotification :

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 

                                               object:nil];


[[NSNotificationCenter defaultCenter] addObserver:self                                                          
selector:@selector(keyboardWillHide:)                                                                  
name:UIKeyboardWillHideNotification
object:nil];

- (IBAction)keyboardWillHide:(NSNotification *)note
{
    // 做自己要做的事情
}


在消息回叫函数中处理--添加按键
- (void)keyboardWillShow:(NSNotification *)note { 
   // create custom button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];

//典型的目标/动作模式
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];


    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES){
            [keyboard addSubview:doneButton];    //控件 也是view 又可以分成多个控件单元 入tableView cell
            break;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值