2015-09-04 83 views
7

當用戶點擊inputAccessoryView中的「附加」按鈕時,我想通過鍵盤創建一個簡單視圖。 事情是這樣的:如何在iOS中通過鍵盤顯示UIView

enter image description here

是否有一個簡單的方法來做到這一點?或者我應該創建我的自定義鍵盤?

回答

9

您可以將新的子視圖添加到您的應用程序窗口。

func attach(sender : UIButton) 
{ 
    // Calculate and replace the frame according to your keyboard frame 
    var customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height-300, width: self.view.frame.size.width, height: 300)) 
    customView.backgroundColor = UIColor.redColor() 
    customView.layer.zPosition = CGFloat(MAXFLOAT) 
    var windowCount = UIApplication.sharedApplication().windows.count 
    UIApplication.sharedApplication().windows[windowCount-1].addSubview(customView); 
} 
+0

是的,這正是我需要的,非常感謝! –

+0

@pavel_s:不客氣。快樂編碼! –

+0

你可以使用'sender.window'而不是'UIApplication.sharedApplication()。windows [...]''? – rintaro

2

您是否找到了解決此問題的有效方法?在iOS9中,您將自定義視圖放置在窗口頂部:UIApplication.sharedApplication()。windows [windowCount-1] .addSubview(customView); 但是,如果鍵盤消失,頂部Windows將被刪除,所以您的customView將被刪除。 期待您的幫助!感謝您的幫助!

+0

請看我的答案,我解決這個問題就像這樣 - http://stackoverflow.com/questions/32598490/show-uiview-with-buttons-over-keyboard-like-in-skype-viber-messengers-swift-i –

0

雖然這可以通過訪問最上面的窗口,但我會避免這樣做,因爲它明顯干擾了Apple的指導方針。

我會做的是解散鍵盤並用相同尺寸的視圖替換它的框架。

可以從列出的鍵盤通知here訪問鍵盤的框架,它們的userInfo包含可用UIKeyboardFrameEndUserInfoKey訪問的鍵。

1

雨燕4.0

let customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height-300, width: self.view.frame.size.width, height: 300)) 
customView.backgroundColor = UIColor.red 
customView.layer.zPosition = CGFloat(MAXFLOAT) 
let windowCount = UIApplication.shared.windows.count 
UIApplication.shared.windows[windowCount-1].addSubview(customView) 
0

斯威夫特4版本:

let customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height - 300, width: self.view.frame.size.width, height: 300)) 
customView.backgroundColor = UIColor.red 
customView.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude) 
UIApplication.shared.windows.last?.addSubview(customView) 

訣竅是將customView添加爲頂部子視圖保存鍵盤UIWindow - 和它發生成爲UIApplication.shared.windows中的最後一個窗口。

0

您絕對可以將視圖添加到您的應用程序的窗口,並且您還可以完全添加另一個窗口。您可以設置其框架和級別。級別可能是UIWindowLevelAlert