我有两个原型单元,两个都有不同的布局。原因是一个细胞会加载雄性,一个细胞会加载雌性。我给了两个单元格一个标识符,现在我试图在每个单元格中加载相关内容。当我加载代码时,它只加载到原型单元格1中。
这是我在cellForRowAtIndexPath中使用的代码:
let cellFemale : Profiles = tableView.dequeueReusableCellWithIdentifier("cellFemale") as Profiles
let cellMale : Profiles = tableView.dequeueReusableCellWithIdentifier("cellMale") as Profiles
if self.profile.genders[indexPath.row] == "female" {
//Adding the textLabel
cellFemale.nameLabel?.text = self.profile.names[indexPath.row]
//Adding the profile picture
var finalImage = UIImage(data: self.profile.images[indexPath.row])
cellFemale.imageLabel?.image = finalImage
//Adding the gender label
//if self.profile.genders[indexPath.row] == "female"{
cellFemale.genderLabel.text = "F"
} else if self.profile.genders[indexPath.row] == "male" {
//Adding the textLabel
cellMale.nameLabel?.text = self.profile.names[indexPath.row]
//Adding the profile picture
var finalImage = UIImage(data: self.profile.images[indexPath.row])
cellMale.imageLabel?.image = finalImage
//Adding the gender label
//if self.profile.genders[indexPath.row] == "female"{
cellMale.genderLabel.text = "M"
}
我忘了添加cellMale作为返回值。但现在我得到了:(配置文件,配置文件)不能转换为UITableViewCell。完整代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellFemale : Profiles = tableView.dequeueReusableCellWithIdentifier("cellFemale") as Profiles
let cellMale : Profiles = tableView.dequeueReusableCellWithIdentifier("cellMale") as Profiles
if self.profile.genders[indexPath.row] == "female" {
//Adding the textLabel
cellFemale.nameLabel?.text = self.profile.names[indexPath.row]
//Adding the profile picture
var finalImage = UIImage(data: self.profile.images[indexPath.row])
cellFemale.imageLabel?.image = finalImage
//Adding the gender label
//if self.profile.genders[indexPath.row] == "female"{
cellFemale.genderLabel.text = "F"
} else if self.profile.genders[indexPath.row] == "male" {
//Adding the textLabel
cellMale.nameLabel?.text = self.profile.names[indexPath.row]
//Adding the profile picture
var finalImage = UIImage(data: self.profile.images[indexPath.row])
cellMale.imageLabel?.image = finalImage
//Adding the gender label
//if self.profile.genders[indexPath.row] == "female"{
cellMale.genderLabel.text = "M"
}
return (cellFemale, cellMale)
}
答案 0 :(得分:2)
您只想将要用于此行的单元格类型出列。此外,您的大部分代码都会在男性和女性案例之间重复出现。我建议:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let isMale = (self.profile.genders[indexPath.row] == "male")
let identifier = isMale ? "cellMale" : "cellFemale"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as Profiles
cell.nameLabel?.text = self.profile.names[indexPath.row]
//Adding the profile picture
let finalImage = UIImage(data: self.profile.images[indexPath.row])
cell.imageLabel?.image = finalImage
//Adding the gender label
cell.genderLabel.text = isMale ? "M" : "F"
return cell
}