结构检查类型 | Swift

Struct check type | Swift

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

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()
}

您应该声明 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()
}