2016-10-07 10 views
1

キーボードに固定されたカスタムUIViewを作成したいが、入力アクセサリビューを使用したが、キーボードが離れているときにはView Controllerに残りません。 iOS Objective-Cの(入力アクセサリビューのような)キーボードに固定するビューコントローラの一番下に制限されたUIViewを持つにはどうすればよいですか?iOS objective-cのキーボードに固執するカスタムUIView

答えて

1

ビューのbottomConstraintためIBOutletを追加します。私はそれがViewControllerのビューの直接的なサブビューであると仮定し、キーボードが隠されているときにはその底部にあるはずです。

@IBOutlet weak var bottomConstraint: NSLayoutConstraint! 

viewWillAppearでキーボード通知登録:viewDidDisappearで

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) 

購読解除:

後でのViewControllerで
NotificationCenter.removeObserver(self) 

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() 
} 

Objective-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]; 
} 
+0

Objective-Cが優先されました。あなたの答えを編集することができればお願いします。 –

+0

@OmotayoOluwatobiよろしくおねがいします;) – alexburtnik

+0

何らかの理由でautolayoutを使用しない場合は、bottomConstraint.constantを変更する代わりにフレームを手動で更新する必要があります。 – alexburtnik

0

あなたのテキストフィールドにinputAccessoryViewを追加する必要があります。

self.mytextField.inputAccessoryView = view; 

・ホープこれはあなたの問題を解決

+0

これは問題を解決しません。キーボードが表示されていないときは、入力アクセサリビューが消えます。私はキーボードが表示されていなくても、私が最初に置いた場所に私の治療法を表示したい。 –

+0

ああ、このケースでは、あなたの下にビューを追加する必要があります参照してください。キーボードのキーボード/キーボードで通知を非表示にすると、そのビューの位置を変更する必要があります。 –

+0

このヘルプはhttp://kingscocoa.com/tutorials/keyboard-content-offset/ –

関連する問題