swift - Tableview 总是回到顶部?离开后到 "detailed"vc?

标签 swift

当用户离开并返回时,如何防止 View Controller 从提要的顶部启动?

基本上,我有主要的VC和详细的VC。当用户选择一个单元格时,它应该跳转到详细的VC。如果她/他回去,她/他应该回到原来的地方。

我知道每次 VC 加载时我的代码都会调用“重新加载数据”,但是如果我不调用该方法,我还有什么其他选择?

这是我的主要 Storyboard的图像(如果有帮助的话)。主 VC(左)是 feed tableView,用户可以在其中点击单元格。当他/她点击单元格时,它会“跳转”到评论表 VC(右)。当他/她完成评论后,她/他可以返回到主 VC 并继续查看 feed。 (理想情况下,除了它不断从最新的帖子加载,而不是让用户回到她/他在提要中的位置)

enter image description here

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostCell
        
        let post: PostModel

        
        post = postList[indexPath.row]
        
        func set(post: PostModel) {
            ImageService.downloadImage(withURL: post.author.patthToImage) { image in
                cell.profileImage.image = image
            }
        }
        set(post: postList[indexPath.row])
        cell.descriptionLabel.numberOfLines = 0 // line wrap
        cell.descriptionLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
        
        cell.descriptionLabel.text = post.message

        cell.authorLabel.text = post.author.username

        cell.timeLabel.text = post.createdAt.calendarTimeSinceNow()
        
        //takes care of post image hidding and showing
        if self.postList[indexPath.row].pathToImage != "" {
            cell.postImage.isHidden = false
            cell.postImage?.downloadImage(from: self.postList[indexPath.row].pathToImage)
        
        } else {
            cell.postImage.isHidden = true

        }
        
        if cell.postImage.isHidden == true {
            cell.postImage.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
            
        }

        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let post: PostModel
        
        post = postList[indexPath.row]
        myIndex = indexPath.row
        myPost = post.postID!
        performSegue(withIdentifier: "segue", sender: self)
        print(myIndex)
        print(post.postID)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        beginBatchFetch()
        
    }

    func beginBatchFetch() {
        fetchingMore = true

        fetchPosts { newPosts in
            self.postList.append(contentsOf: newPosts)

            self.endReached = newPosts.count == 0
            self.fetchingMore = false
            self.tableViewPost.reloadData()
 
        }

    }
    func fetchPosts(completion: @escaping(_ postList:[PostModel])->()) {
        ref = Database.database().reference().child("posts")
        var queryRef:DatabaseQuery
        let lastPost = self.postList.last
        
        if lastPost != nil {
            let lastTimestamp = lastPost!.createdAt.timeIntervalSince1970 * 1000
            queryRef = ref.queryOrdered(byChild: "timestamp").queryEnding(atValue: lastTimestamp).queryLimited(toLast:20)
        } else {
            queryRef = ref.queryOrdered(byChild: "timestamp").queryLimited(toLast:20)
        }
        
        queryRef.observeSingleEvent(of: .value, with: { snapshot in

            var tempPosts = [PostModel]()


            for child in snapshot.children {
                if let childSnapshot = child as? DataSnapshot,
                    let dict = childSnapshot.value as? [String:Any],
                    let author = dict["author"] as? [String:Any],
                    let uid = author["uid"] as? String,
                    let username = author["username"] as? String,
                    let fullname = author["fullname"] as? String,
                    let patthToImage = author["patthToImage"] as? String,
                    let url = URL(string:patthToImage),

                    let pathToImage = dict["pathToImage"] as? String,
                    let likes = dict["likes"] as? Int,
                    let postID = dict["postID"] as? String,
                    let message = dict["message"] as? String,
                    let genre = dict["genre"] as? String,
                    let timestamp = dict["timestamp"] as? Double {


                    let userProfile = UserProfile(uid: uid, fullname: fullname, username: username, patthToImage: url)
                    let post = PostModel(genre: genre, likes: likes, message: message, pathToImage: pathToImage, postID: postID, userID: pathToImage, timestamp: timestamp, id: childSnapshot.key, author: userProfile)
                    tempPosts.insert(post, at: 0)
                }
            }

            //first two
            self.postList = tempPosts
            self.tableViewPost.reloadData()
//            return completion(tempPosts)
        })

最佳答案

正如 Matt 指出的那样,问题在于您正在转至detailVC,然后转回原始VC。这将创建原始 VC 的新实例。

在带有 TableView 的 VC 中,您应该做的是在选择单元格时实例化并显示目标 View Controller 。因此,您应该将 performSegue(withIdentifier: "segue", sender: self) 替换为以下内容:

let storyboard = UIStoryboard(name: "Main", bundle: .main)
var destinationVC = (storyboard.instantiateViewController(withIdentifier: "DestinationVC") as! DestinationViewController)
present(destinationVC!, animated: ture, completion: nil)

注意: View Controller Storyboard标识符可以在界面构建器中设置。因此,如果您想使用这一行:var destinationVC = (storyboard.instantiateViewController(withIdentifier: "DestinationVC") as!DestinationViewController),您首先必须在界面构建器中设置 Storyboard ID :

enter image description here

现在,在您的目标 View Controller 中,您希望使用 dismiss 方法来关闭所呈现的 View Controller ,而不是在按下完成按钮时进行继续操作。

class DestinationViewController: UIViewController {
    @IBAction func backButtonPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

现在,带有 TableView 的原始 VC 保留在内存中,而目标 VC 则显示在其上。当用户按下“后退”按钮时,它将关闭目标 VC,并且原始 VC 应重新出现在您离开时的位置。

关于swift - Tableview 总是回到顶部?离开后到 "detailed"vc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58260379/

相关文章:

ios - 如何删除出现在 uitableview 下方的空白

ios - 我们可以像 iOS 日历应用一样设置 iOS 通知标题时间吗?

swift - 解包 Optional 时意外发现 nil

ios - 录像没有声音?

objective-c - 获取物理引擎移动的对象的方向

ios - 是否可以在不委托(delegate)的情况下使用类似于 webViewFinishLoad 的功能?

ios - Swift 3动画问题

ios - 如何从输入日期开始计算准确的完成天数

ios - Swift 委托(delegate)没有调用

swift - 在 NSTextField 中查找单词的矩形/位置