2016-05-29 88 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