didSelectRowAtIndexPath后延迟

时间:2015-02-03 20:09:13

标签: ios swift uitableview cocoa-touch

我有自定义单元格的桌面视图,当我点击其中一个单元格时,它会向我显示下一个应该是的视图控制器,但是有一段延迟有时会达到5秒。

如何摆脱延迟?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let person = persons[indexPath.row]

    var personViewController: PersonViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PersonViewController") as PersonViewController

    personViewController.name = person.name
    personViewController.imageName = person.image

    self.presentViewController(personViewController, animated: true, completion: nil)
}

PersonViewController

import UIKit

class PersonViewController: UIViewController {

@IBOutlet weak var personImage: UIImageView!
@IBOutlet weak var overlayImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!

var name: String?
var imageName: String?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.personImage.image = UIImage(named: imageName!)
    self.overlayImage.image = UIImage(named: "image_overlay.png") //this is a filter
    self.nameLabel.text = imageName
}

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

}

3 个答案:

答案 0 :(得分:21)

我有同样的问题,似乎这是iOS的错误。 解决了以下解决方案。

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
    Int64(0 * Double(NSEC_PER_SEC))), 
    dispatch_get_main_queue()) { () -> Void in
        self.presentViewController(personViewController, animated: true,completion: nil)
    }

Swift3版本:

DispatchQueue.main.async {
    self.presentViewController(personViewController, animated: true,completion: nil)
}

答案 1 :(得分:6)

也许你会调用方法

[tableView deselectRowAtIndexPath:indexPath animated:NO];

在推送ViewController或其他操作之前

。像

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // 1. manual call this method to deSelect Other Cell
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    // 2. than do other operation
    PushViewController Or Some Animation ....
}

这解决了我的问题。当我为模型样式自定义转换viewController时

答案 2 :(得分:0)

您正在加载两个图像,并在有人点击一个单元格后从故事板中实例化一个视图控制器。这涉及繁重的过程,并且可能需要一些时间,具体取决于视图控制器的复杂程度以及这些图像的大小。

现在您可以将图像加载代码移动到viewDidAppear(),也可以异步加载图像然后分配它们。


另一种方法是使用imageWithContentsOfFile:加载图片。显然这种方法更快,uses less memory

NSString *file = [[NSBundle mainBundle] pathForResource:@"image_name" ofType:@"jpg"];

UIImage *currentImage = [UIImage imageWithContentsOfFile:file];