Skip to content

Instantly share code, notes, and snippets.

@martinlasek
Created November 14, 2019 18:19
Show Gist options
  • Save martinlasek/9e31397567a77939e576071252e408c5 to your computer and use it in GitHub Desktop.
Save martinlasek/9e31397567a77939e576071252e408c5 to your computer and use it in GitHub Desktop.
var username: String = "Anonymous"
var webSocketTask: URLSessionWebSocketTask!
var chatHistory: [String] = []
var safeArea: UILayoutGuide!
let tableView = UITableView()
let messageTextField = UITextField()
let sendButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
safeArea = view.layoutMarginsGuide
navigationItem.title = "Chat Room"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: username, style: .plain, target: nil, action: nil)
setupTableView()
setupMessageTextField()
setupSendButton()
setupWebSocket()
receiveMessage()
}
func setupTableView() {
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
let top = tableView.topAnchor.constraint(equalTo: safeArea.topAnchor)
let width = tableView.widthAnchor.constraint(equalTo: view.widthAnchor)
let height = tableView.heightAnchor.constraint(equalTo: safeArea.heightAnchor, multiplier: 0.33)
NSLayoutConstraint.activate([top, width, height])
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid")
tableView.dataSource = self
}
func setupMessageTextField() {
view.addSubview(messageTextField)
messageTextField.translatesAutoresizingMaskIntoConstraints = false
let top = messageTextField.topAnchor.constraint(equalTo: tableView.bottomAnchor, constant: 5)
let width = messageTextField.widthAnchor.constraint(equalTo: view.widthAnchor)
let height = messageTextField.heightAnchor.constraint(equalToConstant: 35)
NSLayoutConstraint.activate([top, width, height])
messageTextField.backgroundColor = .white
messageTextField.placeholder = "Enter message here.."
messageTextField.clearButtonMode = .whileEditing
}
func setupSendButton() {
view.addSubview(sendButton)
sendButton.translatesAutoresizingMaskIntoConstraints = false
let centerY = sendButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
let centerX = sendButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let width = sendButton.widthAnchor.constraint(equalToConstant: 200)
NSLayoutConstraint.activate([centerY, centerX, width])
sendButton.setTitle("Send Message", for: .normal)
sendButton.setTitleColor(.black, for: .normal)
sendButton.setTitleColor(.blue, for: .highlighted)
sendButton.backgroundColor = .white
sendButton.layer.cornerRadius = 4
sendButton.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment