ChatViewController.swift 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // ChatViewController.swift
  3. // Demo
  4. //
  5. // Created by IEMacBook01 on 23/05/16.
  6. // Copyright © 2016 Iftekhar. All rights reserved.
  7. //
  8. class ChatViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate {
  9. @IBOutlet var tableView : UITableView!
  10. @IBOutlet var buttonSend : UIButton!
  11. @IBOutlet var inputTextField : UITextField!
  12. deinit {
  13. inputTextField = nil
  14. }
  15. var texts = ["This is demo text chat. Enter your message and hit `Send` to add more chat."]
  16. override func viewDidLoad() {
  17. super.viewDidLoad()
  18. inputTextField.inputAccessoryView = UIView()
  19. }
  20. override func viewWillAppear(_ animated: Bool) {
  21. super.viewWillAppear(animated)
  22. NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldDidChange(_:)), name: NSNotification.Name.UITextFieldTextDidChange, object: inputTextField)
  23. }
  24. override func viewWillDisappear(_ animated: Bool) {
  25. super.viewWillDisappear(animated)
  26. NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: inputTextField)
  27. }
  28. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  29. return texts.count
  30. }
  31. func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  32. return 100
  33. }
  34. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  35. return UITableViewAutomaticDimension
  36. }
  37. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  38. let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewCell", for: indexPath) as! ChatTableViewCell
  39. cell.chatLabel.text = texts[(indexPath as NSIndexPath).row]
  40. return cell
  41. }
  42. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  43. tableView.deselectRow(at: indexPath, animated: true)
  44. }
  45. @IBAction func sendAction(_ sender : UIButton) {
  46. if inputTextField.text?.isEmpty == false {
  47. let indexPath = IndexPath(row: tableView.numberOfRows(inSection: 0), section: 0)
  48. texts.append(inputTextField.text!)
  49. inputTextField.text = ""
  50. buttonSend.isEnabled = false
  51. tableView.insertRows(at: [indexPath], with:UITableViewRowAnimation.automatic)
  52. tableView.scrollToRow(at: indexPath, at:UITableViewScrollPosition.none, animated:true)
  53. }
  54. }
  55. @objc func textFieldDidChange(_ notification: Notification) {
  56. buttonSend.isEnabled = inputTextField.text?.isEmpty == false
  57. }
  58. func textFieldDidBeginEditing(_ textField: UITextField) {
  59. }
  60. }