轻拍单元格时,Swift显示不同的图像

时间:2015-07-25 11:39:43

标签: swift

我无法相信我坚持这一点,我从数组中得到了名为Bolognese,Milanese和Pizza的单元格的tableview,因此它只是一个与UIImage所在的另一个detailviewcontroller的tableview。我想点击细胞Bolognese在UIImageView中详细显示博洛尼亚的图片。在详细的VC中遇到问题,我忘记了如何在detailVC中显示来自该数组的图像。我为自己感到羞愧:)。 var array2 = ["1","2","3"] - 这些是imagexcassets中图像的指针谢谢。

Tableviewcontroller

class Hello: UIViewController, UITableViewDelegate, UITableViewDataSource {

var array = ["Bolognese","Milagnese","Pizza"]
var array2 = ["1","2","3"]

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {

    self.tableView.delegate = self
    self.tableView.dataSource = self

    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return array.count
}


 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = self.array[indexPath.row]

    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    self.array2 = self.array

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let driver = segue.destinationViewController as! DetailViewController

    var whatToPass = self.array2
    driver.reciever = whatToPass
}

DetailViewController

class DetailViewController: UIViewController {



@IBOutlet weak var picture: UIImageView!

var reciever = [String]()
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.


    self.picture.image = UIImage(named:receiver)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

1 个答案:

答案 0 :(得分:2)

将目的地中的receiver声明为String

var receiver = ""

然后在prepareForSegue中,获取所选行的indexPath,并使用array2作为索引从indexPath.row中选择图片名称:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let driver = segue.destinationViewController as! DetailViewController

    if let indexPath = tableView.indexPathForSelectedRow() {
        driver.reciever = self.array2[indexPath.row]          
    }        
}

然后,目标视图控制器中viewDidLoad的代码将加载正确的图像:

self.picture.image = UIImage(named:receiver)