【问题标题】:tableview with multiple sections only select one row in each section具有多个部分的表格视图仅在每个部分中选择一行
【发布时间】:2017-02-26 04:57:10
【问题描述】:

我有带有多个部分的自定义单元格的表格视图。每个部分都有多行。每行包含一个标签和一个按钮(单选)。我已经创建了按钮的 IBOutlet 动作。我的要求是在每个部分中只选择一个标签。为了解决这个问题,我实现了下面的代码。 另一个问题是,如果我选择一个单选按钮并滚动到另一部分,单选按钮应显示为选中状态。如何解决这个问题,请告诉我。

let position: CGPoint = sender.convertPoint(CGPointZero, toView: table_view)
if let indexPath = table_view.indexPathForRowAtPoint(position)
{
    let cell = (table_view.cellForRowAtIndexPath(indexPath)! as! PartCell)
    let Section_count = table_view.numberOfSections
    let rowCount = table_view.numberOfRowsInSection(indexPath.section)
    for j in 0..<Section_count
    {
       if j==indexPath.section
       {
          for i in 0..<rowCount
          {
              if i==indexPath.row
              {
                cell.btn_radio.selected=true
              }
              else
              {
                cell.btn_radio.selected=false
              }
          }
     }
 }

【问题讨论】:

  • 无法解决您的问题。请直接解释更多。
  • 我的问题是在表格视图中一次只能选择一个部分的一个单元格。如果我们从同一部分中选择另一个单元格,那么它将被更改或之前被取消选择。
  • 我的一个问题已解决,但我滚动视图然后再次取消选中单选按钮。如何解决。
  • 发生这种情况是因为 TableView 的单元格一旦离开屏幕就会被重用。您需要在某些字典数组中维护选定的单元格。

标签: ios swift xcode uitableview


【解决方案1】:

您可以使用以下示例代码解决:

 var selectedArray : NSMutableArray!

  override func viewDidLoad() {
        super.viewDidLoad()
        selectedArray = NSMutableArray()
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let identifier : String = "reusecell"
      let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: identifier)!

 if (selectedArray? .contains(indexPath))! {
       cell.accessoryType = .checkmark;
        }
          return cell;
     }

  func clickAction(_ sender: AnyObject) {
                    let button = sender as? UIButton
                    let cell = button?.superview?.superview as?   UITableViewCell
                    let indexPath = tblview.indexPath(for: cell!)

                    selectedArray! .removeAllObjects()
                    selectedArray! .add(indexPath)
                    tblview .reloadData()
                    print(indexPath?.row)
                }

【讨论】:

  • 在您实施时,这段代码遇到了哪些问题?
  • 无法将 'NSIndexPath' 类型的值转换为预期的参数类型 '@noescape (Element) throws -> Bool' 这个错误显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 2014-10-14
相关资源
最近更新 更多