시뮬레이터에 텍스트 필드를 눌러도 키보드 자판이 뜨지 않을 경우
시뮬레이터 실행 > 상단 위에 I/O 클릭
Keyboard 클릭 > Toggle Software Keyboard 클릭
cocoaTouch Class 파일 생성 시에 나오는 Also create XIB file은 컨트롤러 같은 경우는 스토리 보드 안에서 작업하기 때문에 컨트롤러가 아닌 경우에는 XIB를 같이 생성
Stretching
- 상황에 따라 전체 크기가 변함
- 1은 늘어나는게 끝까지라고 보면 됨(시작부터 끝까지 전체 다 늘어남 / 0부터 1 사이 값을 넣으면 됨)
가운데를 기준으로 한 픽셀만 잡아서 늘림
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {
// UITableViewDelegate와 DataSource 프로토콜을 사용하기 위해 꼭 구현해야 하는 함수
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ChatDatas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 2로 나눈 나머지 수가 짝수인 경우 이 코드를 실행
if indexPath.row % 2 == 0 {
// IndexPath가 있는걸 사용
let myCell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyCell
myCell.MyCellTextView.text = ChatDatas[indexPath.row]
// 선택했을때 아무런 효과가 나타나지 않음
myCell.selectionStyle = .none
return myCell
// 홀수인 경우 실행
} else {
let yourCell = tableView.dequeueReusableCell(withIdentifier: "yourCell", for: indexPath) as! YourCell
yourCell.YourCellTextView.text = ChatDatas[indexPath.row]
yourCell.selectionStyle = .none
return yourCell
}
}
var ChatDatas = [String]()
@IBOutlet weak var chatTableView: UITableView! {
didSet {
// UITableViewDelegate와 UITableViewDataSource 프로토콜 사용
// 스토리 보드에서 따로 할 수도 있음
chatTableView.delegate = self
chatTableView.dataSource = self
// 구분 선 없애기
chatTableView.separatorStyle = .none
}
}
@IBOutlet weak var InputTextView: UITextView! {
didSet {
InputTextView.delegate = self
}
}
@IBOutlet weak var InputViewBottomMargin: NSLayoutConstraint!
@IBOutlet weak var InputTextViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// 사용하려는 셀 등록
chatTableView.register(UINib(nibName: "MyCell", bundle: nil), forCellReuseIdentifier: "myCell")
chatTableView.register(UINib(nibName: "YourCell", bundle: nil), forCellReuseIdentifier: "yourCell")
// 키보드 관련 옵저버 설정
// 키보드 올라올 때
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
// 키보드 내려올 때
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func KeyboardWillShow(noti: Notification) {
// 텍스트 필드를 눌렀을때 키보드와 텍스트 필드를 같이 올라가게 함
let notiInfo = noti.userInfo!
let KeyboardFrame = notiInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
// 아이폰 x는 기존 아이폰과 달리 safeArea 값만큼 키보다가 더 올라가서 그 값 만큼 빼줘야 함
let height = KeyboardFrame.size.height - self.view.safeAreaInsets.bottom
let animationDuration = notiInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
UIView.animate(withDuration: animationDuration) {
self.InputViewBottomMargin.constant = height
self.view.layoutIfNeeded()
}
}
@objc func KeyboardWillHide(noti: Notification) {
let notiInfo = noti.userInfo!
let animationDuration = notiInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as!
TimeInterval
UIView.animate(withDuration: animationDuration) {
self.InputViewBottomMargin.constant = 0
self.view.layoutIfNeeded()
}
}
// 전송 버튼
@IBAction func SendString(_ sender: Any) {
ChatDatas.append(InputTextView.text)
// 텍스트 입력 후 전송 하면 입력했던 텍스트가 남아있지 않고 지워짐
InputTextView.text = ""
// 테이블 뷰 전체 갱신
//chatTableView.reloadData()
// 마지막 row로 설정 / section도 0부터 시작
let lastInexPath = IndexPath(row: ChatDatas.count - 1, section: 0)
// 테이블 뷰 마지막만 갱신
chatTableView.insertRows(at: [lastInexPath], with: UITableView.RowAnimation.automatic)
chatTableView.scrollToRow(at: lastInexPath, at: UITableView.ScrollPosition.bottom, animated: true)
// 전송 버튼 누른 후 텍스트 뷰 크기를 40으로 돌려놓음
InputTextViewHeight.constant = 40
}
// 텍스트 필드 크기 조절
func textViewDidChange(_ textView: UITextView) {
// 텍스트 크기에 맞춰서 텍스트 뷰 크기가 같이 커지고 작아짐
if textView.contentSize.height <= 40 {
InputTextViewHeight.constant = 40
} else if textView.contentSize.height >= 100 {
InputTextViewHeight.constant = 100
} else {
InputTextViewHeight.constant = textView.contentSize.height
}
}
}
'Swift' 카테고리의 다른 글
Table View (0) | 2021.03.03 |
---|---|
버튼 관련 코드 (0) | 2021.02.24 |
로그인 화면 동적 변환 구조 (0) | 2021.02.17 |
팝업 레이아웃 (0) | 2021.02.16 |
Switch (0) | 2021.02.16 |