ios - 隐藏表格中选定的单元格 - Swift4

标签 ios swift uitableview realm tableview

我有一个包含 4 个地点对象的列表,我从 Realm 数据库中查询这些对象。

Optional(Results<Place> <0x7feaaea447c0> (
    [0] Place {
        name = Daniel Webster Highway;
        country = United States;
        lat = 42.72073329999999;
        lon = -71.44301460000001;
    },
    [1] Place {
        name = District Avenue;
        country = United States;
        lat = 42.48354969999999;
        lon = -71.2102486;
    },
    [2] Place {
        name = Gorham Street;
        country = United States;
        lat = 42.62137479999999;
        lon = -71.30538779999999;
    },
    [3] Place {
        name = Route de HHF;
        country = Haiti;
        lat = 18.6401311;
        lon = -74.1203939;
    }
))

我正在尝试隐藏所选的一个。

例如。当我点击 Daniel Webster Highway 时,我不希望它显示在我的列表中。

enter image description here

如何在 Swift 4 中做到这一点?


代码

//
//  PlaceDetailVC.swift
//  Memorable Places
//
//

import UIKit
import CoreLocation
import RealmSwift

class PlaceDetailVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var address: UILabel!
    @IBOutlet weak var placesTable: UITableView!

    var selectedPlace : Place = Place()
    var selectedTrip : Trip = Trip()
    
    var distances = [ String ]()
    var places : Results<Place>?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        address.text = selectedPlace.name
    
        //register xib file
        placesTable.register(UINib(nibName: "PlaceDetailCell", bundle: nil), forCellReuseIdentifier: "customPlaceDetailCell")
    
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        load()
        
        if selectedPlace != nil && places != nil {
            
            for i in 0..<places!.count {
                
                let latitude = Double(places![i].lat)
                let longitude = Double(places![i].lon)
                
                let currentLatitude = Double(selectedPlace.lat)
                let currentLongitude = Double(selectedPlace.lon)
                
                //print(latitude,longitude,currentLatitude,currentLongitude)
                
                let coordinate = CLLocation(latitude: latitude, longitude: longitude)
                let currentCoordinate = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
                
                let distanceInMeters = coordinate.distance(from: currentCoordinate) // result is in meters
                let distanceInMiles = distanceInMeters/1609.344
                
                distances.append(String(format: "%.2f", distanceInMiles))
                
            }
            
        }
    }
    
    // ---------------------------------------------------------------------------------------------------------
    //MARK - CRUD functions
    
    
    //Read
    func load() {
        places  = selectedTrip.places.sorted(byKeyPath: "name", ascending: true)
        //print(places,"<<<")
        placesTable.reloadData()
        
    }

    
    // ---------------------------------------------------------------------------------------------------------
    //MARK - Table View Datasource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return places?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "customPlaceDetailCell", for: indexPath)
         as! CustomPlaceDetailCell
        
        if selectedPlace.name != nil {
           
            cell.address.text = (places![indexPath.row]["name"] as! String)
            cell.distance.text = distances[indexPath.row]

        }
        
        return cell
    }
    
    // ---------------------------------------------------------------------------------------------------------
    //MARK - Table View Delegate
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        activePlace = indexPath.row
    }
    
    

}

最佳答案

var distances = [ String ]()
var places : Results<Place>?

然后在tableView(_:cellForRow:)

cell.address.text = (places![indexPath.row]["name"] as! String)
cell.distance.text = distances[indexPath.row]

只是不要这样做。这些信息需要同步。

相反,使用另一个类/结构,或者一个可以保存距离和位置的扩展。

var array: [PlaceModel]
struct PlaceModel {
    let place: Place
    let distance: Double //You can use String, but that's bad habit
    //Might want to add the "image link" also?
}

load()中:

array.removeAll()
let tempPlaces = selectedTrip.places.sorted(byKeyPath: "name", ascending: true)
for aPlace in tempPlaces {
    let distance = //Calculate distance for aPlace
    array.append(PlaceModel(place: aPlace, distance: distance)
}

现在,在tableView(_:cellForRow:)中:

let aPlaceModel = array[indexPath.row]
if activePlace == indexPath {
    let cell = tableView.dequeue...
    //Use cellWithImage for that place
    return cell
} else {
    let cell = tableView.dequeue...
    cell.address.text = aPlaceModel.place.name
    cell.distance.text = aPlaceModel.distance
    return cell
}

如果需要,如果需要 heightForRow(如果您希望所有图像均为 80 点,而其余图像为 44 点等,则可以在任何地方保留该逻辑。

tableView(_:didSelectRowAt:) 中,添加 tableView.reloadData(),或更好的 tableView.reloadRows(at: [indexPath] with: 。自动)

注意:代码未经测试,可能无法编译,但您应该明白。

关于ios - 隐藏表格中选定的单元格 - Swift4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174828/

相关文章:

ios - 如何使用代码连接数据源和委托(delegate) - iOS Swift

ios - 无法在 uitableview 中解析 json 文件

ios - 尽管 faSTLane beta 表示构建已上传到 Crashlytics,但没有在 Fabric 中创建新应用

ios - PFQuery findObjectsInBackgroundWithBlock 没有被调用?

ios - 我无法在全局队列(背景模式)上运行进程

ios - 使用特定标识符设置所有单元格的高度?

ios - 从 Objective-C block 中修改存储在实例变量中的信号量

iphone - UIScroll : enable touch event even when it is scrolling

ios - iPhone Xs - 使用 AVCaptureVideoPreviewLayer 时,为什么 UIView 的顶部边框和安全区域的顶部边框之间有巨大的填充?

ios - 无法从照片库中压缩 .mp4 视频