在iOS objective-c中粘贴键盘的自定义UIView

时间:2016-10-07 19:06:15

标签: ios objective-c keyboard

我想制作一个固定在键盘上的自定义UIView,我使用输入附件视图,但当键盘离开时它不会停留在我的视图控制器上。如何在iOS Objective-C中使用UIView将我的视图控制器底部限制在键盘上(如输入附件视图)?

2 个答案:

答案 0 :(得分:2)

为视图的bottomConstraint添加IBOutlet。我认为它是ViewController视图的直接子视图,当键盘被隐藏时它应该在底部。

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

在viewWillAppear中订阅键盘通知:

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.showKeyboard), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.hideKeyboard), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

取消订阅viewDidDisappear:

NotificationCenter.removeObserver(self)

稍后在ViewController中:

func showKeyboard(_ notification: NSNotification) {
    let info = notification.userInfo
    let rectValue = info![UIKeyboardFrameEndUserInfoKey] as? NSValue
    if let keyboardSize = rectValue?.cgRectValue.size {
        bottomConstraint.constant = (keyboardSize?.height)!
        view.layoutIfNeeded()
    }
}

func hideKeyboard(_ notification: Notification) {
    bottomConstraint.constant = 0
    view.layoutIfNeeded()
}

<强>目标-C:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)keyboardWillShow: (NSNotification *) notification {
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    _bottomConstraint.constant = keyboardSize.height;
    [view layoutIfNeeded];
}

-(void)keyboardWillHide: (NSNotification *) notification {
    _bottomConstraint.constant = 0;
    [view layoutIfNeeded];
}

答案 1 :(得分:0)

您需要将inputAccessoryView添加到文本字段中。

例如

self.mytextField.inputAccessoryView = view;

希望这可以解决您的问题