我已经像这样设置了一个自定义公司对象:
class Company: NSObject {
var companyName: String
var companyLogo: String
var stockPrice: String
init(companyName:String, companyLogo:String, stockPrice:String) {
self.companyName = companyName
self.companyLogo = companyLogo
self.stockPrice = stockPrice
}
}
我为每个对象赋予如下属性:
func companyList() -> [Company] {
let apple = Company(companyName: "Apple", companyLogo: "AppleLogo", stockPrice: prices[0])
let google = Company(companyName: "Google", companyLogo: "GoogleLogo", stockPrice: prices[1])
let twitter = Company(companyName: "Twitter", companyLogo: "TwitterLogo", stockPrice: prices[2])
let tesla = Company(companyName: "Tesla", companyLogo: "TeslaLogo", stockPrice: prices[3])
let samsung = Company(companyName: "Samsung", companyLogo: "SamsungLogo", stockPrice: prices[4])
return [apple, google, twitter, tesla, samsung]
}
我想用 Company 对象的数据填充 tableview 的标签 - 例如,我想设置 tableview 的标签以读取所有公司名称 - 使用公司名称字符串的硬编码数组(即不作为对象)很简单:
cell.textLabel.text = companyNames[indexPath.row]
既然我有一个 Company 对象,我该如何做同样的事情?
听起来您想将一个数组(公司)转换为另一个数组(公司名称)。这是 map
的好用处:
let companyNames = companyList().map({ $0.companyName })
cell.textLabel.text = companyNames[indexPath.row]
或者,你可以先找到合适的公司,然后是它的名字:
cell.textLabel.text = companyList()[indexPath.row].companyName
不需要中间数组,所以我建议第二个选择。
关于ios - 读取自定义对象的数据以填充表格 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41620754/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |