Изменить UIButton на ячейку в UITableView - PullRequest
0 голосов
/ 08 июля 2019

Я пытаюсь изменить кнопку и ее функцию в зависимости от выбранной ячейки.В настоящее время у меня есть список больниц, которые увидит пользователь.Нажатая ячейка откроет деталь, состоящую из двух меток, изображения и кнопки.Все работает как напечатано, кроме кнопки.Я бы хотел, чтобы он менялся в каждой ячейке в соответствии с номером телефона данной больницы.Есть идеи?

import UIKit
var hospital = ["Mercy Medical Center"]
var hospitalDesc = ["Roseburg"]
var myIndex = 0

class PhoneBookTableViewController: UITableViewController {

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return hospital.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PBCell", for: indexPath)

        cell.textLabel?.text = hospital[indexPath.row]
        cell.detailTextLabel?.text = hospitalDesc[indexPath.row]

        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}


class PhoneBookDetail: UIViewController{

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descLabel: UILabel!
    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var callHospital: UIButton!

    let phoneVA = "tel://5412175034"

    override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.text = hospital[myIndex]
        descLabel.text = hospitalDesc[myIndex]
       myImageView.image = UIImage(named: hospital[myIndex] + ".jpg")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Ответы [ 2 ]

1 голос
/ 08 июля 2019

Объявите структуру для управления данными больницы и передайте или напрямую назначьте, используя метод prepareforsegue. Вот модифицированная версия вашего кода @Wesley Bryant

struct Hospital{
    var name = ""
    var location = ""
    var contact = ""
    var image = ""
}


class PhoneBookTableViewController : UITableViewController{

    var  hospitals :[Hospital] = [Hospital]()
    var myIndex = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        hospitals.append(Hospital(name: "Mercy Medical Center", location: "Roseburg", contact: "tel://5412175034", image: "0.jpg"))

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return hospitals.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PBCell", for: indexPath)
        let hospital = hospitals[indexPath.row]
        cell.textLabel?.text = hospital.name
        cell.detailTextLabel?.text = hospital.location

        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        myIndex = indexPath.row
        performSegue(withIdentifier: "Detail", sender: self)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Detail" {
            let destinationVC = segue.destination as! PhoneBookDetail
            let hospital = hospitals[myIndex]
            destinationVC.selectedHospital = hospital
            //OR
            destinationVC.callHospital.setTitle(hospital.contact, for: UIControl.State.normal)
            destinationVC.titleLabel.text = hospital.name
            destinationVC.descLabel.text = hospital.location
            destinationVC.myImageView.image = UIImage(named: hospital.image)
        }
    }

}


class PhoneBookDetail: UIViewController{
    var selectedHospital : Hospital = Hospital()

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descLabel: UILabel!
    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var callHospital: UIButton!



    override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.text = selectedHospital.name
        descLabel.text = selectedHospital.location
        myImageView.image = UIImage(named: selectedHospital.image)

        let phoneVa = selectedHospital.contact
        print(phoneVa)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Измените "идентификатор segue" согласно вашему требованию

0 голосов
/ 08 июля 2019

Прежде всего вы должны объявить метод prepareSegue в PhoneBookTableViewController после метода tableView

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segue" {
//write the name of view controller where you want to show the details
            let destinationVC = segue.destination as! ViewController

//make one global variable in viewController where you want to show the details and set that variable in this prepare method
//here phoneNo is global variable of viewController where you want to show the data

            destinationVC.phoneNo. = phoneVA
            destinationVC.delegate = self
        }
    }

(пожалуйста, добавьте более подробную информацию здесь)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...