iOS編程:實(shí)現(xiàn)類似微信的對(duì)話框

今天實(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了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容