今天實(shí)現(xiàn)一個(gè)類似微信的對(duì)話框練手,也算是新手入門,UI的編程伴隨很多繁瑣的問題,記錄在這里。
問題一:實(shí)現(xiàn)點(diǎn)擊輸入框(UITextField),鍵盤顯示出來時(shí),自動(dòng)將整個(gè)view上浮,當(dāng)輸入結(jié)束時(shí),將view再沉下來,這是個(gè)非?;A(chǔ)的功能。
實(shí)現(xiàn)方式:
1. 在viewDidLoad方法中,加入監(jiān)聽鍵盤出現(xiàn)和隱藏事件:
//observe keyboard show/hide to move view up/down
NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillShow:", name:UIKeyboardWillShowNotification, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillHide:", name:UIKeyboardWillHideNotification, object:nil)
2. 實(shí)現(xiàn)兩個(gè)事件處理方法:keyboardWillShow/keyboardWillHide
func keyboardWillShow(aNotification:NSNotification) {
? ? moveView(aNotification, show:true)
}
func keyboardWillHide(aNotification:NSNotification) {
? ? moveView(aNotification, show:false)
}
func moveView(aNotification:NSNotification, show:Bool) {
? ? let userInfo:NSDictionary= aNotification.userInfo!
? ? //get which key is really is not important
? ? let keyboardInfo:AnyObject? = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)
? ? if let frame = keyboardInfo?.CGRectValue{
? ? ? ? if(show) {
? ? ? ? view.frame.origin.y-= frame.height
? ? ? ? }else{
? ? ? ? ? ? view.frame.origin.y+= frame.height
? ? ? ? }
? ? }
? ? view.setNeedsDisplay()
}
3. 輸入完成不應(yīng)當(dāng)隱藏鍵盤,而是用戶點(diǎn)擊上面對(duì)話框的區(qū)域(即不點(diǎn)擊鍵盤區(qū)域,才隱藏),所以要加一個(gè)TapGestureRecognizer,實(shí)現(xiàn)方法:
@IBActionfunctapOnSpace(sender:UITapGestureRecognizer) {
? ? let tapPoint = sender.view?.frame
? ? if let origin = (tapPoint?.origin){
? ? ? ? if view.frame.contains(origin){
? ? ? ? ? ? talkTextField.resignFirstResponder()
? ? ? ? }
? ? }
}
問題二:實(shí)現(xiàn)UITableView中的TableViewCell的大小,隨著內(nèi)容的大小而變化。
搜了一下網(wǎng)上,都說要實(shí)現(xiàn)func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat方法,但后來發(fā)現(xiàn),并不需要這么做。直接在functableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) ->UITableViewCell里重寫cell的大小就OK了。關(guān)鍵在于要調(diào)用sizeToFit重算一下大小。
cell.wordsLabel.sizeToFit()
問題三:Autolayer布局的問題
兩個(gè)label(name和words),左右相鄰。設(shè)置了name與左邊框連接,右邊與words連接,words與右邊框保持100的距離。系統(tǒng)提示說兩個(gè)label的位置是“二義”的。原因出在哪里?
關(guān)鍵在于要設(shè)置兩個(gè)參數(shù):Hugging和Content Compression的Priority。我希望優(yōu)先顯示name的內(nèi)容,所以它的compression priority要大于words,同時(shí)如果有多余空間,我希望給words用,所以它的hugging priority是大于name的。這樣就OK了。