1)Storyboard로 Tableview를 그리는것을 시도
2)delegate의 개념에 대해서도 정리
3)Alert으로 text를 입력하는 코드를 적용
4)TextField로 text를 입력하는 코드를 적용
iOS text field in table view cell
import UIKit
class TodoListPage: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
}
extension TodoListPage: UITableViewDelegate, UITableViewDataSource {
//행의 개수
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath)
// 셀 내부에서 특정 태그 (123) 값을 가진 기존 텍스트 필드가 있는지 확인합니다.
// as? UITextField 로 타입을 캐스팅 합니다. 성공하면 해당 텍스트필드를 참조하고, 실패하면 nildl 할당됩니다.
// 이 줄의 목적은 셀 내에 이미 태그 값이 123인 텍스트 필드가 있는지 판별하는 것입니다.
var textField = cell.viewWithTag(123) as? UITextField
// 텍스트 필드가 없는 경우, 어떻게 표시할건지를 지정합니다.
if textField == nil {
textField = UITextField(frame: cell.contentView.bounds)
textField?.placeholder = "텍스트 입력"
textField?.tag = 123
textField?.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
cell.contentView.addSubview(textField!)
}
// 인덱스 번호를 표시합니다.
textField?.text = "\(indexPath.row + 1)"
// 설정된 셀을 반환합니다.
return cell
}
// 사용자 정의 함수: 텍스트를 셀에 업데이트하는 메서드
func updateText(_ newText: String, for indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.textLabel?.text = newText
}
}
// text field의 내용이 변경될 때 호출되는 메서드
@objc func textFieldDidChange(_ textField: UITextField) {
guard let text = textField.text,
let row = textField.tag as Int? else {
return
}
updateText(text, for: IndexPath(row: row, section: 0))
}
}