【问题标题】:Swift : Single Selection with UITableViewsSwift:使用 UITableViews 进行单选
【发布时间】:2015-04-11 10:36:40
【问题描述】:

我有一个启用单选的常规 UITableView。我的问题是,如果用户选择多行,那么原始行仍然被选中。我也有一个问题,无论我设置 cell.selectionStyle = UITableViewCellSelectionStyle.Blue

我的视图控制器在 Storyboard 中定义。

表格视图

  • 内容:动态原型
  • 选择:单选
  • 在触摸 [X] 时显示选择
  • 背景:黑色
  • 索引行限制:0

表格单元格视图

  • 风格:自定义
  • 选择:蓝色
  • 背景:黑色

以下是一些截图:

这是我的代码:

class AreaViewController: UITableViewController
{

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.backgroundColor = backgroundColour
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("areacell", forIndexPath: indexPath) as! UITableViewCell
        cell.selectionStyle = UITableViewCellSelectionStyle.Blue

        cell.textLabel?.text = "Cell Contents"
        cell.textLabel?.textColor = UIColor.whiteColor()

        return cell
    }

     override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    {
         let cell = tableView.dequeueReusableCellWithIdentifier("areacell", forIndexPath: indexPath) as! UITableViewCell

    }
}

我一定遗漏了一些明显的东西,但我没有看到任何不标准的东西。

【问题讨论】:

    标签: uitableview swift


    【解决方案1】:

    来自UITableViewCell Class Reference

    UITableViewCellSelectionStyleBlue 单元格有默认背景 选择时的颜色。

    在 iOS 7 中,选择颜色不再是蓝色。采用 改为 UITableViewCellSelectionStyleDefault。

    如果您想为选定的单元格设置特殊的背景颜色,您必须设置单元格的backgroundView

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell
    
        // Configure the cell...
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.redColor()
        cell.selectedBackgroundView = backgroundView
    
        return cell
    }
    

    看起来像这样:

    【讨论】:

    • 谢谢紫软。我之前曾尝试过这段代码,但它只能工作。突出显示为红色,但只有当您移开手指时“触摸”该行时,它才会作为我的原始帖子变灰。
    • 我无法重复此操作,它可以正常工作。您是否在代码中的某处调用 deselectRowAtIndexPath()
    • 或者您是否不小心使用了deselectRowAtIndexPath 而不是didSelectRowAtIndexPath?由于代码完成,不久前我也发生了同样的事情。很难看出区别:-)
    • 不,我已经检查了我的代码,并且我从未在整个项目中调用 deselectRowAtIndexPath。现在有人已经检查了我的理智,我将尝试从头开始重新创建视图。我会让你知道我是怎么过的。谢谢。
    【解决方案2】:

    啊!我终于找到了。好像我在调用 let cell = tableView.dequeueReusableCellWithIdentifier("areacell", forIndexPath: indexPath) 为! didSelectRowAtIndexPath 方法中的 UITableViewCell。删除它会导致一切重新开始工作。确实很明显。感谢您帮助 zisoft 让我走上正确的道路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多