美文网首页
iMessages聊天界面

iMessages聊天界面

作者: gale_小米 | 来源:发表于2022-01-05 17:51 被阅读0次
import UIKit
import AddressBookUI  //联系人
import ContactsUI  //9.0以后推荐使用

class ViewController: UIViewController,UITextViewDelegate, UINavigationControllerDelegate,CNContactPickerDelegate,ABPeoplePickerNavigationControllerDelegate,
                      UIImagePickerControllerDelegate,UITableViewDelegate,UITableViewDataSource{

    @IBOutlet weak var contentText: UITextView!
    //底部view的高度约束
    
    @IBOutlet weak var bottomHeightLayout: NSLayoutConstraint!
    //UITextView的高度约束
    @IBOutlet weak var textHeightLayout: NSLayoutConstraint!
    //底部view的底部到self.view的约束
    @IBOutlet weak var buttomViewLayout2: NSLayoutConstraint!
    
    @IBOutlet weak var addImageView: UIImageView!
    
    @IBOutlet weak var sendMessageView: UIImageView!
    
    @IBOutlet weak var contacts: UITextField!
    
    @IBOutlet weak var messageTable: UITableView!
//    var image: UIImageView = UIImageView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
    
    var meassageData:Array<MessageModel>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        contentText.delegate = self
        meassageData = Array()
        
//        self.navigationController?.setToolbarHidden(false, animated: false)
//        let rightButtom = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.edit, target: self, action: #selector(self.Edit))
//        self.navigationItem.rightBarButtonItem = rightButtom
//        self.title = "消息"
//        self.navigationController?.navigationBar.backgroundColor = UIColor.white
        //隐藏
        self.navigationController?.navigationBar.isHidden = true
        //添加手势
        let addTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.addImageAction(gest:)))
        self.addImageView.isUserInteractionEnabled = true
        self.addImageView.addGestureRecognizer(addTapGesture)
        let sendMessageGesture = UITapGestureRecognizer(target: self, action: #selector(self.sendMessageAction(gest:)))
        self.sendMessageView.isUserInteractionEnabled = true
        self.sendMessageView.addGestureRecognizer(sendMessageGesture)
        
        //添加通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShow(noti:)), name: ViewController.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardHide(noti:)), name: ViewController.keyboardWillHideNotification, object: nil)
        self.messageTable.separatorStyle = .none
        self.messageTable.delegate = self
        self.messageTable.dataSource = self
        self.messageTable.reloadData()
        
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return meassageData!.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = Bundle.main.loadNibNamed("MessageTableViewCell", owner: nil, options: nil)?.first as! MessageTableViewCell
        let model = self.meassageData![indexPath.row] as MessageModel
        if model.icon == nil {
            cell.messageContent.text = model.message
            cell.messageImage.isHidden = true
            cell.messageContent.isHidden = false
        }else {
            cell.messageImage.isHidden = false
            cell.messageContent.isHidden = true
            cell.messageImage.image = model.icon
        }
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = self.meassageData![indexPath.row] as MessageModel
        if model.icon == nil {
            var size : CGSize
            let tmpSize = CGSize(width: UIScreen.main.bounds.width - 30, height: 0)
            let messageStr:NSString = model.message! as NSString
            size = messageStr.boundingRect(with: tmpSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17)], context: nil).size
            return size.height + 30
        }else{
            return 152
        }
    }
    
    
    
    //添加联系人
    @IBAction func addContacts(_ sender: UIButton) {
        if #available(iOS 9.0, *) {
            print("systemVersion=\(UIDevice.current.systemVersion)")
            let contactController2 = CNContactPickerViewController()
            contactController2.displayedPropertyKeys = [CNContactPhoneNumbersKey]
            contactController2.delegate = self
            self.present(contactController2, animated: true)
        }else{
            let contactController = ABPeoplePickerNavigationController()
            contactController.peoplePickerDelegate = self
            self.present(contactController, animated: true)
        }
        
    }
    
    
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        let phoneNumbers = contacts[contacts.startIndex].phoneNumbers
        let numStr = phoneNumbers[phoneNumbers.startIndex].value.stringValue
        self.contacts.text = numStr
    }
    
    //获取联系人信息
    func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
        let unmInfo = ABRecordCopyValue(person, kABPersonPhoneProperty)
        let numRef:ABMultiValue = Unmanaged.fromOpaque(unmInfo!.toOpaque()).takeUnretainedValue()
        let num = ABMultiValueCopyValueAtIndex(numRef, 0)
        let numStr:String = Unmanaged<AnyObject>.fromOpaque(num!.toOpaque()).takeUnretainedValue() as! String
        self.contacts.text = numStr
    }
    
    //添加图片
    @objc func addImageAction( gest : UITapGestureRecognizer){
        print("addImageAction")
        let pic = UIImagePickerController()
        pic.delegate = self
        self.present(pic, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let model = MessageModel(_icon: info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
        self.meassageData!.append(model)
        picker.dismiss(animated: true, completion: nil)
        self.messageTable.reloadData()
    }
    
    @objc func sendMessageAction( gest : UITapGestureRecognizer){
        let message:String = self.contentText.text
        let model = MessageModel(_message: message)
        self.meassageData?.append(model)
        self.contentText.text = ""
        self.textHeightLayout.constant = 56
        self.bottomHeightLayout.constant = 63
        self.buttomViewLayout2.constant = 0
        self.contentText.resignFirstResponder()
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
            self.messageTable.reloadData()
        }
    }
    
    
    
    @objc func Edit(){
        print("Edit")
        let viewCon = ViewController2()
        self.navigationController?.pushViewController(viewCon, animated: true)
    }
    
    
    //监听软键盘弹出消息
    @objc func keyboardShow(noti : Notification){
        let info = noti.userInfo
        let heightValue = info?[ViewController.keyboardFrameEndUserInfoKey] as! NSValue
        let height = heightValue.cgRectValue.height
        var time: TimeInterval = 0
        let timeValue = info?[ViewController.keyboardAnimationDurationUserInfoKey] as! NSNumber
        timeValue.getValue(&time)
        self.buttomViewLayout2.constant = height
        UIView.animate(withDuration: time) {
            self.view.layoutIfNeeded()
        }
    }
    
    //隐藏软键盘
    @objc func keyboardHide(noti : Notification){
        let info = noti.userInfo
        var time: TimeInterval = 0
        let timeValue = info?[ViewController.keyboardAnimationDurationUserInfoKey] as! NSNumber
        timeValue.getValue(&time)
        self.buttomViewLayout2.constant = 0
        UIView.animate(withDuration: time) {
            self.view.layoutIfNeeded()
        }
    }
    
    //动态设置view的约束
    func textViewDidChange(_ textView: UITextView) {
        //其中常量值 56 63 取自storyboard排版里面的值
        if textView.contentSize.height <= 56 {
            self.textHeightLayout.constant = 56
            self.bottomHeightLayout.constant = 63
        }else if(textView.contentSize.height < 100){
            self.textHeightLayout.constant = textView.contentSize.height
            self.bottomHeightLayout.constant = textView.contentSize.height + 7
        }else{
            self.textHeightLayout.constant = 100
            self.bottomHeightLayout.constant = 107
        }
        UIView.animate(withDuration: 0.3) {//用于更新页面布局,可以用于自动布局的动画
            self.view.layoutIfNeeded()
        }
    }
    
    
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        contentText.resignFirstResponder()
    }

}

  1. model
import Foundation
import UIKit

class MessageModel : NSObject{
    var icon : UIImage?
    var message : String?
    
    init( _icon : UIImage) {
        self.icon = _icon
    }
    
    init( _message : String) {
        self.message = _message
    }
}

相关文章

网友评论

      本文标题:iMessages聊天界面

      本文链接:https://www.haomeiwen.com/subject/ygnhqrtx.html