【问题标题】:Hide Selected Cell from the Table - Swift4从表格中隐藏选定的单元格 - Swift4
【发布时间】:2018-11-06 15:19:49
【问题描述】:

我有一个包含 4 个 places 对象的列表,我从 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 时,我不希望它显示在我的列表中。

如何在 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
    }
    
    

}

【问题讨论】:

  • 您需要更新包含这些值的数组。要么删除它,要么因为看起来你用“图像”替换它,只需“标记它”,重新加载该行,检查它是否被“标记”并将正确的单元格或“正常单元格”出列。
  • 您应该使用用于在表格视图中显示这些结果的代码来编辑您的问题,否则很难用代码给出准确的答案。
  • @DávidPásztor 我很抱歉,完全没有想到这一点。我更新了我的帖子。

标签: ios swift uitableview realm tableview


【解决方案1】:
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 (例如,如果您希望所有图像都为 80pt 而其余图像为 44pts 等),则将该逻辑保留在您想要的任何地方。

tableView(_:didSelectRowAt:) 中,添加tableView.reloadData(),或者更好的是tableView.reloadRows(at: [indexPath] with: .automatic)

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

【讨论】:

    【解决方案2】:

    您可以将所选行的索引从 placesVC 传递到您的 PlaceDetailVC 并在

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
        if indexPath.row == passedIndex {
            return 0
        }
    
        return 70
    }
    

    将单元格高度设置为 0 以隐藏单元格。

    【讨论】:

    • 我喜欢你的思维方式。我们根本不需要从数组中删除任何东西或维护另一个数组。用 1 行添加 if-check,完成,这很酷;
    • 第一次尝试有效,但我注意到一个警告。似乎它仍然显示大约 2 个像素的距离值。看到这张图片:i.imgur.com/itaMyRd.png
    • 您的 PlaceDetailCell 构建是否有约束?如果您选择了第二行,请告诉我它的外观
    • 如果我点击第二行,我得到了这个:i.imgur.com/MVCwtAm.png
    • 很奇怪。好的,如果 indexPath.row ==passedIndex { cell.distance.isHidden = true } else { cell.distance.isHidden = false} ,那么简单的解决方法是在 cellForRowAt 中使用,但这非常难看。可能是因为错误的约束或分隔符而显示了 2 个像素。
    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多