2016-05-29 79 views
0

具有包含2种类型的结构 - 图像和文本。有一个数组,它将被添加。如何在cellForRowAtIndexPath中进行类型检查?结构检查类型| Swift

struct typeArray { 
    var text: String? 
    var image: UIImage? 

    init(text: String){ 
     self.text = text 
    } 

    init(image: UIImage){ 
     self.image = image 
    } 
} 

var content = [AnyObject]() 

图像添加按钮:

let obj = typeArray(image: image) 
    content.append(obj.image!) 
    self.articleTableView.reloadData() 

文本添加按钮:

let obj = typeArray(text: self.articleTextView.text as String!) 
    self.content.append(obj.text!) 
    self.articleTableView.reloadData() 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 

    if content[indexPath.row] == { 

     let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Text Cell", forIndexPath: indexPath) as! TextTableViewCell 

     cell.textArticle.text = content[indexPath.row] as? String 

     return cell 

    } 

    else if content[indexPath.row] == { 

     let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Image Cell", forIndexPath: indexPath) as! ImageTableViewCell 

     cell.backgroundColor = UIColor.clearColor() 
     cell.imageArticle.image = content[indexPath.row] as? UIImage 

     return cell 
    } 
    return UITableViewCell() 
} 
+0

'cellForRowAtIndexPath'是不是要建立阵列的地方;这个函数将被调用的顺序不能保证;你需要使用提供的'indexPath'来确定你正在操作哪一行 – Paulw11

+0

@ Paulw11在这种情况下你有什么建议? –

+0

我建议你有一个单一的结构数组,其中每个结构体可以保存文本或图像,然后在'cellForRowAtIndexPath'中使用它。 – Paulw11

回答

0

你应该声明你content数组来保存你的typeArray结构的实例;

var content = [typeArray]() 

然后该结构的实例添加到阵列:

let obj = typeArray(image: image) 
content.append(obj) 
self.articleTableView.reloadData() 

然后你就可以在你的cellForRowAtIndexPath使用 -

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let rowStruct = content[indexPath.row] { 
    if let text = rowStruct.text { 
     let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Text Cell", forIndexPath: indexPath) as! TextTableViewCell 
     cell.textArticle.text = text 
     return cell 
    } else if let image = rowStruct.image { 
     let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Image Cell", forIndexPath: indexPath) as! ImageTableViewCell 
     cell.backgroundColor = UIColor.clearColor() 
     cell.imageArticle.image = image 
     return cell 
    } 
    return UITableViewCell() 
} 
+0

让行rowStruct = content [indexPath.row],“无法调用非函数类型的值vc.typeArray” –

+0

我做了,如果让文本=内容[indexPath.row]。文本和它的作品很好 –

+0

您需要添加结构的实例,而不是图像到数组。看我的编辑 – Paulw11