我正在重新创建gmail应用程序的简单版本,并且遇到了一个小烦人的问题,我似乎无法解决该问题。
我看了一些this one之类的答案,但没有运气。
总体概念与gmail用户单击单元格相同,图像显示x倍的时间然后消失。
如您所见,点击和实际呈现的图像之间会稍有延迟。
这是我用来执行实际图像加载的CustomeIvageView:
import UIKit
class CustomImageView: UIImageView {
func loadImage(urlString: String){
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
if let err = err {
print("failed to fetch user profile photoes", err)
}
guard let imageData = data else {return}
let photoImage = UIImage(data: imageData)
DispatchQueue.main.async {
self.image = photoImage
}
}.resume()
}
}
然后在我的视图控制器中,我有这个:
class PictureViewController: UIViewController {
var snap: Snap? {
didSet{
usernameLabel.text = snap?.fromUser?.username
guard let imageUrl = snap?.imageUrl else {return}
previewImageView.loadImage(urlString: imageUrl)
}
}
lazy var previewImageView: CustomImageView = {
let iv = CustomImageView()
iv.contentMode = .scaleAspectFill
return iv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(previewImageView)
previewImageView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
guard let timer = snap?.timer else {return}
let delayTime = Double(timer)
delay(delayTime){
self.handleCancel()
}
}
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
func handleCancel(){
self.dismiss(animated: false) {
}
}
编辑:显示我在哪里设置PictureViewController。为了简洁起见,我省略了代码。
import UIKit
import Firebase
class ChatViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout{
var recievedSnaps = [Snap]()
var mappedSnaps = [String: [Snap]]()
let cellId = "cellId"
let picMessageView = PictureViewController()
override func viewDidLoad() {
super.viewDidLoad()
//Removed code for brevity
}
//OMITTED CODE FOR BREVITY
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ChatCell
picMessageView.snap = cell.snap
self.present(picMessageView, animated: false, completion: nil)
}
}
答案 0 :(得分:0)
我尝试了您的代码,除了关闭PictureViewController时,该代码工作正常。您需要在主UI线程中调用该dismiss,以使其能够正确执行。
func handleCancel(){
DispatchQueue.main.async {
self.dismiss(animated: false, completion: nil)
}
}