首页 > 解决方案 > swift中tableview单元格之间的差距

问题描述

从服务器获取数据后,我将其显示在表格视图中。当我用一些动画删除任何单元格时,我在单元格之间获得了一些空间。仅当我删除数组的最后一个索引时才会发生这种情况。如果我要删除任何其他单元格,它工作正常,但对于最后一个单元格,问题正在发生。我的代码有什么问题吗?

我的代码是:-

 func userDislikeButtonWasTappaed(dsender: UIButton){
    dsender.pulsate()
    guard let indexPath = tableView.indexPathForRow(at: dsender.convert(dsender.frame.origin, to: tableView)) else {
        return
    }


    let cell = tableView.cellForRow(at: indexPath) as? MatchingUsersTVCell
    let tag = dsender.tag

    //Remove the user data from the array for the perticular indexpath
    if modelNameArray.count > 0{
        let userid = userIdArray[tag]
        totalScoreArray.remove(at: tag)
        fullAdressArray.remove(at: tag)
        modelArray.remove(at: tag)
        userIdArray.remove(at: tag)
        modelNameArray.remove(at: tag)
        age.remove(at: tag)

        let uid: Int = UserDefaults.standard.value(forKey: "User_Id") as! Int
        let accessToken: String = UserDefaults.standard.value(forKey: "access_token") as! String

        apiRequest.disLikeTheUser(uid, userid, accessToken) { (disLikedUser) in
            UIView.animate(withDuration: 0.95, animations: {
                self.tableView.deleteCellWithAnimationRight(cell: cell!)
            }) { (_) in
                self.tableView.reloadWithAnimation()
            }


        }
    }

}


func deleteCellWithAnimationRight(cell: UITableViewCell) {

    let tableViewHeight = self.bounds.size.height
    let tableViewWidth = self.bounds.size.width
    var delayCounter = 0
    cell.contentView.layer.opacity = 0.4
    cell.transform = CGAffineTransform(translationX: -(2 * tableViewWidth) , y: 0)
    cell.contentView.layer.opacity = 0.0
    UIView.animate(withDuration: 7.6, delay: 0.08 * Double(delayCounter),usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
        //             cell.contentView.layer.opacity = 0.0
        cell.transform = CGAffineTransform.identity
    }, completion: nil)
    delayCounter += 1

}


func reloadWithAnimation() {
    self.reloadData()
    let tableViewHeight = self.bounds.size.height
    let tableViewWidth = self.bounds.size.width
    let cells = self.visibleCells
    var delayCounter = 0
    for cell in cells {
        cell.contentView.layer.opacity = 1.0
        cell.transform = CGAffineTransform(translationX: 0, y: tableViewHeight)
    }
    for cell in cells {
        cell.contentView.layer.opacity = 1.0

        UIView.animate(withDuration: 3, delay: 0.08 * Double(delayCounter),usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {

            cell.transform = CGAffineTransform.identity
            cell.clipsToBounds = true
        }, completion: nil)
        delayCounter += 1
    }

}


 func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return modelArray.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "MatchingUsersTVCell") as? MatchingUsersTVCell else{
        return UITableViewCell()
    }

    cell.profileImageView?.image = UIImage(named: "bg0")
    //Get the image from image string
    if let imageUrl = URL(string: modelArray[indexPath.row]){

        // Use the pinrest to set image to the profile image view

        let resource = ImageResource(downloadURL:  imageUrl)
        cell.profileImageView?.kf.setImage(with: resource)

    }


    // set the profile image corner radius
    cell.profileImageView.layer.cornerRadius = 40.0;
    cell.profileImageView.clipsToBounds = true

    //Set the name data fetching from the server to the name label
    cell.profileNameLbl.text = modelNameArray[indexPath.row]


    //Set the Adress data fetching from the server to the Adress label

    cell.profileAddressLbl.text = fullAdressArray[indexPath.row]
    cell.ageLabel.text = String(describing: age[indexPath.row]) 



    let likeUid = userIdArray[indexPath.row]

    cell.heartBtn.tag = indexPath.row
    cell.deselectBtn.tag = indexPath.row
    cell.parentVC = self
    cell.index = indexPath.row
    // Add action for heart button
    cell.heartBtn.addTarget(self, action: #selector(userLikeButtonWasTappaed(sender:)), for: .touchUpInside)

    // Add action for deselect button
    cell.deselectBtn.addTarget(self, action: #selector(userDislikeButtonWasTappaed(dsender:)), for: .touchUpInside)


    if #available(iOS 11.0, *) {
        cell.profileImageView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner, .layerMinXMinYCorner, . layerMaxXMaxYCorner, .layerMaxXMinYCorner]
        cell.gradientimage.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]

    } else {
        // Fallback on earlier versions
    }


    return cell
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let passingUserId = userIdArray[indexPath.row]
    Constant.const.DETAIL_VIEW_LIKE_CLOSE_ICON_BOOL = true

    //Save the userid in user default in swift
    UserDefaults.standard.set(passingUserId, forKey: Constant.const.USER_ID_CONST)
    if #available(iOS 13.0, *) {
        let storyboard = (UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "UserDetailTableViewController") as? UserDetailTableViewController)!

        storyboard.modalPresentationStyle = .fullScreen
        //            present(storyboard, animated: true, completion: nil)
        self.navigationController?.pushViewController(storyboard, animated: true)
    } else {
        let storyboard = (UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "UserDetailTableViewController") as? UserDetailTableViewController)!

        storyboard.modalPresentationStyle = .fullScreen
        //                      present(storyboard, animated: true, completion: nil)
        self.navigationController?.pushViewController(storyboard, animated: true)
    }


    //present(storyboard!, animated: true, completion: nil)
}


  func getUserData(_ userId: Int, accessToken: String) {
    view.showAnimatedGradientSkeleton()
    apiRequest.getUserData(userId, accessToken) { (Person) in
        if let result = Person?.Result{
            for i in result{
                let firstName = i.FirstName
                let CityName = i.CityName
                let StateName = i.StateName
                let TotalScore = i.TotalScore
                let fullAdress = "\(CityName),\(StateName)"
                let ImagePath = i.ProfileImage
                let modelImage = BASE_URL + ImagePath
                let userAccountId = i.UserAccountId
                self.age.append(i.Age)
                let nameWithAge = firstName + ", "
                //Append all the data to the array
                self.totalScoreArray.append(TotalScore)
                self.fullAdressArray.append(fullAdress)
                self.modelNameArray.append(nameWithAge)
                self.modelArray.append(modelImage)
                self.userIdArray.append(userAccountId)
                //                    self.userAgeArray.append(userAge)

            }

            // Reload table view after getting all the user from server
            self.view.hideSkeleton()
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
}

标签: swiftuitableviewanimation

解决方案


推荐阅读