【问题标题】:Toggle UIBarButtonItem on KeyboardDidShow在 KeyboardDidShow 上切换 UIBarButtonItem
【发布时间】:2014-10-12 17:21:11
【问题描述】:

目的:我试图在键盘出现时用“隐藏键盘”UIBarButtonItem 切换“保存”UIBarButtonItem(然后在单击“隐藏键盘”按钮时执行相反的操作)。

到目前为止,我已经创建了两个 UIBarButtonItem 并将它们都连接到 Interface Builder。

@property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *hideKeyButton;

这是我到目前为止在我的主目录中设置的代码:

- (void)keyboardDidShow:(NSNotification *)aNotification {
    // Show HideKey Button
    // Hide Save Button
}

- (void)keyboardWillHide:(NSNotification *)aNotification {
    // Show Save Button
    // Hide HideKey Button
}

在 Interface Builder 上,默认情况下存在“保存”按钮。以编程方式,如何显示 HideKey 按钮和隐藏 Save 按钮?谢谢。

【问题讨论】:

    标签: ios uinavigationcontroller uibarbuttonitem keyboard-events


    【解决方案1】:

    有两个部分可以完成这项工作。

    首先,您需要注册通知,您可以在 viewDidLoad 中添加以下内容:

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

    其次,在您的事件处理程序中,只需设置按钮:

    - (void)keyboardDidShow:(NSNotification *)aNotification {
        self.navigationItem.rightBarButtonItem = hideKeyButton;
    }
    
    - (void)keyboardWillHide:(NSNotification *)aNotification {
        self.navigationItem.rightBarButtonItem = saveButton;
    }
    

    【讨论】:

    • 工作就像一个魅力,谢谢。 Xcode 在对象前添加下划线的原因是什么。示例:_saveButton 与 saveButton 相对。
    • 它们实际上指向同一个东西。您可以做以下三件事之一:1)使用_saveButton,2)使用self.saveButton; 3) 将@synthesize saveButton 添加到yr .m 的开头,在@implementation 之后,现在你不需要self。更多,你可以简单地说saveButton。这三个确实是一样的。
    • 我不知道!我对@synthesize 和“自我”感到非常困惑。谢谢你为我解决这个问题。仍然是一名正在接受培训的程序员。 :)
    【解决方案2】:

    我不会使用 IB 来完成这项任务,而是以编程方式完成。

    类似这样的:

    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                                 target:self
                                                                                 action:@selector(saveButtonPressed:)];
    [self.navigationItem setRightBarButtonItem:saveButton];
    

    并以类似的方式创建和设置 HideKey 按钮。

    那么,当然你可能想要缓存UIBarButtonItems,为它们设置惰性@properties。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多