【问题标题】:How can I create a UITableView for each property in a model?如何为模型中的每个属性创建 UITableView?
【发布时间】:2020-03-15 13:27:24
【问题描述】:

我有一个看起来像这样的结构:

internal class RemoteProfileModel: Decodable {
  let userId: String
  let company: String
  let email: String
  let firstName: String
  let lastName: String
  let department: String
  let jobTitle: String
  let pictureUri: URL?
  let headerUri: URL?
  let bio: String
  let updatedDate: Date
}

我需要在UITableView 中列出这些属性。我还需要为某些属性使用不同的单元格类型。

我在想也许我应该将此结构转换为键/值对字典,并使用键来确定单元格类型。

这可能吗?还有另一种方法可以实现这一目标吗?我不确定是否可以将结构转换为字典,所以不确定这是最好的方法吗?

【问题讨论】:

    标签: ios swift uitableview dictionary struct


    【解决方案1】:

    将类转换为字典,

    class RemoteProfileModel: Decodable {
        let userId: String
        let company: String
        let email: String
    
        let firstName: String
        let lastName: String
        let department: String
    
        let jobTitle: String
        let pictureUri: URL?
        let headerUri: URL?
    
        let bio: String
        let updatedDate: Date
    
    
        init() {
            userId = "666"
            company = "AAPL"
            email = "hehe@163.com"
    
            firstName = "user"
            lastName = "test"
            department = "guess"
    
            jobTitle = "poor iOS"
            pictureUri = URL(string: "wrong")
            headerUri = URL(string: "none")
    
            bio = "China"
            updatedDate = Date()
    
        }
    
        func listPropertiesWithValues(reflect: Mirror? = nil) -> [String: Any]{
            let mirror = reflect ?? Mirror(reflecting: self)
            if mirror.superclassMirror != nil {
                self.listPropertiesWithValues(reflect: mirror.superclassMirror)
            }
            var yourDict = [String: Any]()
            for (index, attr) in mirror.children.enumerated() {
                if let property_name = attr.label {
                    //You can represent the results however you want here!!!
                    print("\(index): \(property_name) = \(attr.value)")
                    yourDict[property_name] = attr.value
                }
            }
            return yourDict
        }
    }
    

    这样调用:

        let profile = RemoteProfileModel()
        profile.listPropertiesWithValues()
    

    在 Swift 调试和反射中,

    镜像描述了构成特定实例的部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2022-01-21
      • 2012-06-14
      • 1970-01-01
      相关资源
      最近更新 更多