2015-01-21 86 views
3

以我LeftViewController这是滑出菜单,有表视图 我建立表头为这将适用于表格单元阵列索引超出范围

var locals:[Local]=[Local(title: "Market",image:"ic_cars_black_24dp.png"), 
        Local(title: "Compare", image: "ic_bar_chart_24dp.png"), 
        Local(title: "Wishes",image: "ic_fantasy_24dp.png"), 
        Local(title: "Buy",image: "ic_put_in_24dp.png")] 

var globals:[Global]=[Global(title: "Auction Latest",image:"ic_cars_black_24dp.png"), 
        Global(title: "Auction Past", image: "ic_bar_chart_24dp.png"), 
        Global(title: "Auction Recent",image: "ic_fantasy_24dp.png"), 
        Global(title: "Buy",image: "ic_put_in_24dp.png")] 

每个变量这是我的函数与UITableView的

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 2 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.locals.count + self.globals.count 
} 

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let headerMenuCell = tableView.dequeueReusableCellWithIdentifier("HeaderMenuCell") as HeaderMenuCell 

    switch(section){ 
    case 0: 
     headerMenuCell.headerMenuLabel.text="Local" 
    case 1: 
     headerMenuCell.headerMenuLabel.text="Auction" 
    default: 
     headerMenuCell.headerMenuLabel.text="Others" 
    } 

    return headerMenuCell 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cellIdentifier = "Cell" 
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as Cell 
    switch(indexPath.section){ 
    case 0: 
     cell.configureForLocal(locals[indexPath.row]) 
    case 1: 
     cell.configureForGlobal(globals[indexPath.row]) 
    default: 
     cell.textLabel?.text="Others" 
    } 
    return cell 
} 

关注这是我的Cell类

class Cell: UITableViewCell { 
@IBOutlet weak var imageView: UIImageView! 
@IBOutlet weak var imageNameLabel: UILabel! 

func configureForLocal(locals: Local) { 
    imageView.image = UIImage(named: locals.image) 
    imageNameLabel.text = locals.title 
} 

func configureForGlobal(globals: Global) { 
    imageView.image = UIImage(named: globals.image) 
    imageNameLabel.text = globals.title 
} 

}

请帮忙,为什么我发现数组索引超出范围?

回答

3

tableView:numberOfRowsInSection:有一个section参数,它是希望行数的部分 - 您需要返回指定部分的正确计数,而不是所有部分的总计数。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    switch section { 
    case 0: return locals.count 
    case 1: return globals.count 
    default: fatalError("unknown section") 
    } 
} 

否则它看起来很好。

+0

“VAR全局:[全局] = [全局(标题: ”拍卖最新“,图像” ic_cars_black_24dp.png“),全球 (标题: ”拍卖过去“,图像 ”ic_bar_chart_24dp.png“), 全球(标题:“近期拍卖”,图片:“ic_fantasy_24dp.png”)]“如果我这样设置,当我在numberOfRowInSection中返回”4“时,再次出现该错误。 – 2015-01-21 04:28:48

+0

您需要为请求的部分返回适当的计数,无论是全局部分还是本地部分。 – 2015-01-21 04:32:16

+0

现在我在本地部分有4行,在全局部分有3行,我应该在numberOfRowInSection返回什么先生? – 2015-01-21 04:34:27