结构检查类型|迅速

时间:2016-05-29 09:47:16

标签: ios swift uitableview tableview tableviewcell

具有包含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()
}

1 个答案:

答案 0 :(得分: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()
}