안녕하세요:)
오늘은 현상금 랭킹 앱을 만드려보려고 합니다.
- 원피스 각 캐릭터에 대한 현상금과 사진을 셀 형식으로 만든다.
- 각 캐릭터에 맞는 셀을 터치하면 새로운 View가 Modal 형태로 나타난다.
- 새로운 Modal에서 선택한 캐릭터의 이름과 현상금이 나오도록 만든다.
1. Table View
2. Segue
3. Custom Cell
4. Protocol
5. UIImage
import UIKit
class BountyViewController: UIViewController {
let nameList = ["brook", "chopper", "franky", "luffy", "nami", "robin", "sanji", "zoro"]
let bountyList = [33000000, 50, 4400000, 300000000, 160000000, 800000000, 77000000, 1200000000]
// DetailViewController에게 Data 전달
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
let vc = segue.destination as? DetailViewController
if let index = sender as? Int {
vc?.name = nameList[index]
vc?.bounty = bountyList[index]
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
// DataSource
extension BountyViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bountyList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ListCell else {
return UITableViewCell()
}
let img = UIImage(named: "\(nameList[indexPath.row]).jpg")
cell.imageView?.image = img
cell.nameLabel.text = nameList[indexPath.row]
cell.bountyLabel.text = "\(bountyList[indexPath.row])"
return cell
}
}
// Delegate
extension BountyViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("--> \(indexPath.row)")
performSegue(withIdentifier: "showDetail", sender: indexPath.row)
}
}
// Custom Cell
class ListCell: UITableViewCell {
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var bountyLabel: UILabel!
}
Table View에 대한 자세한 내용은 Apple Developer에서 확인하세요.
📗테이블뷰 바로가기
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var bountyLabel: UILabel!
var name: String?
var bounty: Int?
@IBAction func closeButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func updateUI() {
if let name = self.name, let bounty = self.bounty {
let img = UIImage(named: "\(name).jpg")
imgView.image = img
nameLabel.text = name
bountyLabel.text = "\(bounty)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
}