ios swift - 具有多个数据源/笔尖的表视图

时间:2016-03-12 16:41:56

标签: ios swift

我想创建一个表视图,从两个不同的数据源加载其数据,并根据它是哪一个选择一个特定的nib。如何创建混合来自两个对象数组的元素的提要?

我正在考虑创建一个对象数组,其中的对象按日期排序。然后,我会在我的cellforrowatindexpath方法中检查每个对象的类型,并使用对应的nib。

这是最有效的方法吗?

谢谢

2 个答案:

答案 0 :(得分:2)

创建单个对象数组并在cellForRowAtIndexPath中正确处理它们是一种很好的方法。

您应该使用viewDidLoadregisterNibForCellReuseIdentifier中使用表格视图注册每个笔尖。确保为每个reuseIdentifier使用不同的cellForRowAtIndexPath,然后在确定应该是哪种类型的单元格后,在override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(UINib(nibName: "fooCell", bundle: .mainBundle()), forCellReuseIdentifier: "fooCellIdentifier"); tableView.registerNib(UINib(nibName: "barCell", bundle: .mainBundle()), forCellReuseIdentifier: "barCellIdentifier"); } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell? if (indexPathIsFooCell(indexPath)) { cell = tableView.dequeueReusableCellWithIdentifier("fooCellIdentifier", forIndexPath: indexPath) } else { cell = tableView.dequeueReusableCellWithIdentifier("barCellIdentifier", forIndexPath: indexPath) } //customise the cell return cell! } 中将正确的类型出列。

body

答案 1 :(得分:2)

以下是可以帮助您的另一种解决方案

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
    var cell = tableView.dequeueReusableCellWithIdentifier("relatedTableViewCell") as? relatedTableViewCell
    if cell == nil {
        let nib:Array = NSBundle.mainBundle().loadNibNamed("relatedTableViewCell", owner: self, options: nil)
        cell = nib[0] as? relatedTableViewCell
    }
    let info = relatedQuizArr.objectAtIndex(indexPath.row) as!  relatedInfo
   cell?.relatedImage.sd_setImageWithURL(NSURL(string: info.rqImage!))
   cell?.relatedLabel.text = (String: info.rqName!)
        cell?.rQuizView.layer.shadowOffset = CGSizeMake(-1, 1)
        cell?.rQuizView.layer.shadowOpacity = 0.4
    return cell!
    } else {
        var cell = tableView.dequeueReusableCellWithIdentifier("relatedTableViewCell") as? relatedTableViewCell
        if cell == nil {
            let nib:Array = NSBundle.mainBundle().loadNibNamed("relatedTableViewCell", owner: self, options: nil)
            cell = nib[0] as? relatedTableViewCell
        }
        if indexPath.row == 0 {
            let label = UILabel(frame: CGRectMake(22, 10, 200, 40))
            label.font = label.font.fontWithSize(25)
            label.textAlignment = NSTextAlignment.Center
            label.text = "Featured Quiz"
            cell!.addSubview(label)
        }
        else {
        }
        let info = featuredQuizArray.objectAtIndex(indexPath.row) as!  relatedInfo
        cell?.relatedImage.sd_setImageWithURL(NSURL(string: info.featuredqImage!))
        cell?.relatedLabel.text = (String: info.featuredqName!)
        cell?.rQuizView.layer.shadowOffset = CGSizeMake(-1, 1)
        cell?.rQuizView.layer.shadowOpacity = 0.4
        return cell!
    }

希望它会有所帮助。