테이블 뷰 컨트롤러?
데이터를 목록 형태로 제공, 특정 항목 선택 - 세부사항 표시. (메일, 알람, 연락처)
기본 세팅
import UIKit
var items = ["고양이","강아지","치이카와"]
var itemsImageFile = ["cat2.jpeg","dog2.jpg","hi.jpg"]
class TableViewController: UITableViewController {
@IBOutlet var tvListView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1 //테이블 안에 섹션이 하나
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = items[(indexPath as NSIndexPath).row]
//셀의 text lable 앞에 선언한 items를 대입
cell.imageView?.image = UIImage(named: itemsImageFile[(indexPath as NSIndexPath).row])
return cell
}
이 상태에서 목록 삭제 동작 추가하기
delete 버튼 글자 삭제로 변경
override func tableView (_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "삭제"
}
//여기서 편집 버튼으로 순서 변경 (정렬)
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem
//주석으로 제공되어있음.. 주석 풀기만 하면 사용 가능
}
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
let itemToMove = items[(fromIndexPath as NSIndexPath).row]
let itemImageToMove = itemsImageFile[(fromIndexPath as NSIndexPath).row]
items.remove(at: (fromIndexPath as NSIndexPath).row)
itemsImageFile.remove(at: (fromIndexPath as NSIndexPath).row)
items.insert(itemToMove, at: (to as NSIndexPath).row)
itemsImageFile.insert(itemImageToMove, at: (to as NSIndexPath).row)
}
새 목록 추가하기
-addViewController
@IBAction func btnAddItem(_ sender: UIButton) {
items.append(tfAddItem.text!)
itemsImageFile.append("snow3.jpg")
tfAddItem.text=""
_ = navigationController?.popViewController(animated: true) //루트 뷰 컨트롤러로 돌아감
}
-TableViewController
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_ animatedL: Bool){
tvListView.reloadData() //추가된 리스트 다시 보여주기...
}
//상세페이지
import UIKit
class DetailViewController: UIViewController {
@IBOutlet var lblItem: UILabel!
var receiveItem = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
lblItem.text = receiveItem
}
func receiveItem(_ item: String){ //mainView 에서 변수를 받기 위한 함수
receiveItem = item
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
-tableViewController
// 세그웨이를 이용해서 뷰를 이동하는 함수
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
if segue.identifier == "sgDetail" {
let cell = sender as! UITableViewCell
let indexPath = self.tvListView.indexPath(for: cell)
let detailView = segue.destination as! DetailViewController
detailView.receiveItem(items[((indexPath! as NSIndexPath).row)])
}
}
** 도전과제
Add View 화면에서 아이콘 선택할 수 있도록 만들어보기
import UIKit
class AddViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var tfAddItem: UITextField!
@IBOutlet var pickedImage: UIImageView!
@IBOutlet var imagePickerView: UIPickerView!
var selectedItem = ""
override func viewDidLoad() {
super.viewDidLoad()
imagePickerView.delegate = self
imagePickerView.dataSource = self
pickedImage.image = UIImage(named:itemsImageFile[0])
// Do any additional setup after loading the view.
}
@IBAction func btnAddItem(_ sender: UIButton) {
items.append(tfAddItem.text!)
itemsImageFile.append(selectedItem)
tfAddItem.text=""
_=navigationController?.popViewController(animated: true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1 //pickerView에 표시되는 열의 개수
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return itemsImageFile.count
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 80
}
//각 뷰 컴포넌트 UIView 타입으로 넘겨줌
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let imageView = UIImageView(image: (UIImage(named: itemsImageFile[row])))
imageView.frame = CGRect(x: 0, y: 0, width: pickerView.frame.size.width, height: 80)
return imageView
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickedImage.image = UIImage(named: itemsImageFile[row])
selectedItem = itemsImageFile[row]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
해결!
사실 이렇게 하면 전역변수인 itemsImageFiles가 늘어날때마다 피커뷰 행도 계속 늘어나는 문제가 있는데, 이는 그냥 여기서 따로 변수 선언해주기만 하면 되므로... 귀찮아서 한 번에 넣어버렸다.
'Study > Swift' 카테고리의 다른 글
do - try - catch 문 (0) | 2025.01.02 |
---|---|
[스위프트 기초] 자동 레이아웃 (1) | 2024.12.27 |
[스위프트 기초] 뷰가 보일때 호출되는 함수 순서 (0) | 2024.12.27 |
[swift error] Thread 1: breakpoint 1.1 (1) (0) | 2024.12.27 |
[swift error] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier reuseIdentifier (0) | 2024.12.27 |
댓글