iOS编程:实现类似微信的对话框

今天实现一个类似微信的对话框练手,也算是新手入门,UI的编程伴随很多繁琐的问题,记录在这里。

问题一:实现点击输入框(UITextField),键盘显示出来时,自动将整个view上浮,当输入结束时,将view再沉下来,这是个非常基础的功能。

实现方式:

1. 在viewDidLoad方法中,加入监听键盘出现和隐藏事件:

//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. 实现两个事件处理方法: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. 输入完成不应当隐藏键盘,而是用户点击上面对话框的区域(即不点击键盘区域,才隐藏),所以要加一个TapGestureRecognizer,实现方法:

@IBActionfunctapOnSpace(sender:UITapGestureRecognizer) {

    let tapPoint = sender.view?.frame

    if let origin = (tapPoint?.origin){

        if view.frame.contains(origin){

            talkTextField.resignFirstResponder()

        }

    }

}


问题二:实现UITableView中的TableViewCell的大小,随着内容的大小而变化。

搜了一下网上,都说要实现func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat方法,但后来发现,并不需要这么做。直接在functableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) ->UITableViewCell里重写cell的大小就OK了。关键在于要调用sizeToFit重算一下大小。

cell.wordsLabel.sizeToFit()


问题三:Autolayer布局的问题

两个label(name和words),左右相邻。设置了name与左边框连接,右边与words连接,words与右边框保持100的距离。系统提示说两个label的位置是“二义”的。原因出在哪里?

关键在于要设置两个参数:Hugging和Content Compression的Priority。我希望优先显示name的内容,所以它的compression priority要大于words,同时如果有多余空间,我希望给words用,所以它的hugging priority是大于name的。这样就OK了。

你可能感兴趣的:(iOS编程:实现类似微信的对话框)