我已经设置了这样的自定义公司对象:
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]
如果我有公司对象,我怎么能做同样的事情呢?
答案 0 :(得分:0)
听起来您想将一个阵列(公司)转换为另一个阵列(公司名称)。这适用于map
:
let companyNames = companyList().map({ $0.companyName })
cell.textLabel.text = companyNames[indexPath.row]
或者,你可以先找到合适的公司,然后是它的名字:
cell.textLabel.text = companyList()[indexPath.row].companyName
哪个不需要中间数组,所以我建议第二个选择。
答案 1 :(得分:0)
您应该考虑创建一个UITableViewCell
子类,它需要Company
属性...
CompanyCell: UITableViewCell {
var company: Company {
didSet {
textLabel.txt = company.companyName
}
}
}
然后在你的视图控制器中,
cell.company = companies[indexPath.row]
答案 2 :(得分:0)
var companies: [Company]!
companies = companyList()
tableView(_:numberOfRowsInSection:)
中的行数时,请返回companies.count
cell.textLabel.text = companies[indexPath.row].companyName
tableView(_:cellForRowAt:)
和其他值