class AnimalTableViewController: UITableViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail"{
if let dvc = segue.destination as? DetailViewController{
if let selectRow = tableView.indexPathForSelectedRow?.row{
dvc.infoView1 = animalArray[selectRow]
dvc.navigationItem.title = animalArray[selectRow]
}
}
}
}
// 利用 tableView.indexPathForSelectedRow?.row 得到使用者按那一個row
// 找到 要傳送的 string -> animalArray[selectRow]
// 然後 只訂到 dvc.infoView1
// 設定 dvc 的 title -> dvc.navigationItem.title
}
class DetailViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
@IBOutlet weak var myLabel: UILabel!
var infoView1:String? // 新增一個 infoView1
override func viewDidLoad() {
super.viewDidLoad()
myLabel.text = infoView1
if let name = infoView1{
myImageView.image = UIImage(named: name)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
----------------------------------------------------
客製化的tableview cell
首先新增一個 tableviewcell 的 檔案
然後在main.storyboard 裡面新增一個image view 和 label在 cell -> conview
然後把這兩個連結過去
class SpecialTableViewCell: UITableViewCell {
@IBOutlet weak var special: UIImageView!
@IBOutlet weak var specialLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
然後在 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
試著轉型成剛剛的 SpecialTableViewCell
如果可以的話... 設定 imageview.image 和 label.text
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? SpecialTableViewCell{
cell.special?.image = UIImage(named: animalArray[indexPath.row])
cell.specialLabel?.text = animalArray[indexPath.row]
return cell
}else{ // 轉型失敗
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = animalArray[indexPath.row]
cell.imageView?.image = UIImage(named: animalArray[indexPath.row])
return cell
}
// Configure the cell...
}
沒有留言:
張貼留言