swift uitableview didSelectRowAtIndexPath未被调用

时间:2015-01-13 11:02:41

标签: uitableview swift didselectrowatindexpath

我正在开展天气预报项目。我从数据库列出城市。当我点击一个城市时,另一个视图控制器应该打开。但是当我点击某个城市时,didSelectRowAtIndexPath功能无效。

这是我的代码:

class HavaViewController: UIViewController, UITableViewDataSource, UITableViewDelegate  {
    @IBOutlet var havatableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.havatableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier")
        havatableView.dataSource = self

        // XMl Parse
        let url = NSURL(string: "http://haberftp.trt.net.tr/haberservis/havadurumu.aspx")
        let data = NSData(contentsOfURL: url!)
        if(data != nil){
        let dataxml = NSString(data:data!, encoding: NSUTF8StringEncoding)
        let xml = SWXMLHash.parse(dataxml!)

        for merkez in xml["HavaTahmini"]["Merkez"] {
            var cityName = merkez.element?.attributes["MerkezAdi"]
            for gun in merkez["Gun"] {
              //  println(gun.element?.attributes["Tarih"])
                var tarih = gun.element?.attributes["Tarih"]
                var endusuk = gun["EnDusuk"].element?.text
                var enyuksek = gun["EnYuksek"].element?.text
                var durum = gun["DurumuKod"].element?.text


            }
        }


        }

     self.loadData()





        println("hava")
        // Do any additional setup after loading the view.
    }
    func newCityWeather(cityName: String, tarih: String, endusuk: String, enyuksek: String, durum: String){

        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate )
        var context: NSManagedObjectContext = appDel.managedObjectContext!
        var newCity = NSEntityDescription.insertNewObjectForEntityForName("Hava", inManagedObjectContext: context) as NSManagedObject


        newCity.setValue(cityName, forKey: "sehir")
        newCity.setValue(tarih, forKey: "tarih")
        newCity.setValue(endusuk, forKey: "endusuk")
        newCity.setValue(endusuk, forKey: "enyuksek")
        newCity.setValue(endusuk, forKey: "endusuk")
        newCity.setValue(endusuk, forKey: "durum")

        context.save(nil)

        //  println(newCity)


    }
    func newCity(cityName: String){

        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate )
        var context: NSManagedObjectContext = appDel.managedObjectContext!
        var newCity = NSEntityDescription.insertNewObjectForEntityForName("Sehirler", inManagedObjectContext: context) as NSManagedObject


        newCity.setValue(cityName, forKey: "sehir")
        context.save(nil)



    }
    func loadData() {
        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate )
        var context: NSManagedObjectContext = appDel.managedObjectContext!


        var request = NSFetchRequest(entityName: "Sehirler")
        request.returnsObjectsAsFaults = false
        var results: NSArray = context.executeFetchRequest(request, error: nil)!
        if results.count>0 {

            for res in results {
            //    println(res)
            }

        }else {
            println("sonuc yok")

        }


    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 81
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell : HavaTableViewCell = tableView.dequeueReusableCellWithIdentifier("mycell") as HavaTableViewCell
        var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate )
        var context: NSManagedObjectContext = appDel.managedObjectContext!


        var request = NSFetchRequest(entityName: "Sehirler")
        request.returnsObjectsAsFaults = false
        var results: NSArray = context.executeFetchRequest(request, error: nil)!
        if results.count>0 {
            var cities = [String]()

            for result in results {
                 var res = result as NSManagedObject
                let city = res.valueForKey("sehir") as String
                cities.append("\(city)")
            }

            cell.setCell(cities[indexPath.row])


        }




        return cell
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
      println("click")
        println(indexPath.row)
     //   performSegueWithIdentifier("showHavaDetay", sender: self)
    }



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



}

3 个答案:

答案 0 :(得分:1)

你错过了这个:

havatableView.delegate = self

答案 1 :(得分:1)

我在比较两个相同的代码示例时遇到了同样的问题,其中一个正在运行而另一个没有调用didSelectRowAtIndexPath

至少有两种方法可以解决这个问题:

1)在代码本身:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    table.delegate = self
    table.dataSource = self 
//data source might be already set if you see contents of the cells
//the main trick is to set delegate
}

2)使用故事板或文档大纲(这是我的问题导致故事板更改在.swift控制器类中不可见。

打开文档大纲并Control + Press TableView delegate 您会看到两个名为“dataSource”和“ViewController”的商店 将它们逐个拖动到包含{{1}}(右侧到黄色圆圈)

就是这样!

答案 2 :(得分:0)

您必须设置delegate的{​​{1}}属性才能启动UITableView功能。仅仅声明该类支持didSelectRowAtIndexPath协议是不够的。

UITableViewDelegate

将委托设置为self告诉havatableView.delegate = self 当前类具有UITableView

中的函数

有关详细信息:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html#//apple_ref/occ/instp/UITableView/delegate