簡體   English   中英

swift中單個對象的NSNotification

[英]NSNotification for single object in swift

我有兩個文本字段,topTextField 和 bottomTextField,分別位於屏幕的頂部和底部。 當它出現時,bottomTextField 隱藏在虛擬鍵盤后面,以便修復我使用 NSNotification 偵聽虛擬鍵盤並在發生這種情況時向上滑動視圖的問題。 然而,只要鍵盤出現在屏幕上,視圖就會向上滑動,包括當 topTextField 成為第一響應者時,有效地將其移出屏幕。 這是代碼:

    func subscribeToKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: bottomTextField)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: bottomTextField)
}

func unsubscribeToKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: bottomTextField)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: bottomTextField)
}

我最初將“nil”作為方法末尾的對象參數,這是我開始尋找將行為隔離到bottomTextField 的方法的時候。

我假設解決這個問題的關鍵是在這些方法中的對象參數中,我目前正在傳遞bottomTextField。 Apple 的 NSNotificationCenter 文檔說該參數用於

觀察者想要接收其通知的對象; 也就是說,只有此發送者發送的通知才會傳遞給觀察者。

如果傳遞 nil,通知中心不會使用通知的發送者來決定是否將其傳遞給觀察者。

我將其解釋為我們可以調用特定對象進行偵聽,因此在本例中為 bottomTextField。 但是,當我將它們從“nil”更改為“bottomTextField”時,視圖不再向上滑動,而 bottomTextField 仍處於隱藏狀態。 我是否錯誤地解釋了這一點? 如果沒有,我該怎么做才能讓它發揮作用? 如果我不正確,有沒有辦法隔離單個對象以使用 NSNotification 偵聽?

對象應該是nil 不是文本框

在處理程序中檢查鍵盤“覆蓋”了哪些文本字段

-(void)keyboardHandler:(NSNotufication *)note {

Cgrect keyboardFrame = [note.userInfo[keyboardframe] cgrectvalue]; // dont remember the key name (answering from my phone :)). Check uiapplication header. 

// check which text field is covered and move it

// you may need to convert the rect coordinates using:

cgrect windowFrame = [[[uiapplication sharedapplication] keyWindow] convertRect:textfieldFrame fromView:textfield.superView]];

If (windowFrame is covered by keyboard ...) { 
    Move text field....
}

希望它足夠清楚....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM