【问题标题】:Hiding one button out of three buttons using iOS Swift使用 iOS Swift 隐藏三个按钮中的一个按钮
【发布时间】:2016-02-21 15:24:24
【问题描述】:

我有一个大约有 5 个单元格(行)的 UITableView。每个单元格(行)都添加了三个 UIButtons 作为相应单元格的子视图。

Row1: Button1 Button2 Button3 // 所有这些按钮都有 tag = row_number = 1

Row2: Button1 Button2 Button3 // 所有这些按钮都有 tag = row_number = 2

Row3: Button1 Button2 Button3 // 所有这些按钮都有 tag = row_number = 3

Row4: Button1 Button2 Button3 // 所有这些按钮都有 tag = row_number = 4

注意: 所有行的 Buttons1 都连接到同一个 IBAction。 相似地, 所有行的 Buttons2 都连接到同一个 IBAction。很快... 我完全能够检测到在单元格中按下了哪个按钮。我正在为此使用标签。

我想做以下事情:

  1. 如果从一行中按下一个按钮,它应该在按下时隐藏,而同一行中的所有其他按钮应保持显示。一段时间后,如果从同一行按下另一个按钮,则新按下的按钮应隐藏,而先前隐藏的按钮应返回到视图中。

目前我可以隐藏按下的第一个按钮,但如果之后按下同一行的另一个按钮,则无法将其恢复。

  1. 这是否也可以跟踪同一行内先前按下的按钮?

请指导我应该如何实现。

提前致谢。

【问题讨论】:

  • 有很多方法可以解决这个问题。一种解决方案可能是将UITableViewCell 子类化并在其中进行自己的实现。您可以更轻松地控制每个单元格的内容。

标签: ios swift algorithm


【解决方案1】:

由于您的问题一次只影响一个单元格,我们可以专注于一个单元格。

您应该使用一个 UITableViewCell 子类来保留对其按钮的引用,并且是它们的操作的 target

因此子类可以很好地封装所有与视图相关的界面更改。

然后您可以使用Delegation 将操作传播到您的视图控制器并处理实际逻辑。

编辑

关于您的第二个问题,使用此设置,通过在每次按下时将每个按钮的索引附加到 [Int] 来轻松跟踪单元格内的按钮按下顺序。

【讨论】:

  • 完美,谢谢大家的回答。同时,我还通过为按钮创建全局数组,然后在每个 IBAction 中将其他按钮的隐藏属性设置为 FALSE,找到了问题 1 的解决方案。
  • 从架构的 OOP 角度来看,这是一个可怕的解决方案。考虑关注点分离封装
【解决方案2】:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
 {
  let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell



  // add a line for each one of the buttons
   cell.btn1.addTarget(self, action: "handleButtonPressed:", forControlEvents: .TouchUpInside)
   cell.btn2.addTarget(self, action: "handleButtonPressed:", forControlEvents: .TouchUpInside)
   cell.btn3.addTarget(self, action: "handleButtonPressed:", forControlEvents: .TouchUpInside)
   cell.btn4.addTarget(self, action: "handleButtonPressed:", forControlEvents: .TouchUpInside)


   return cell
  }

   @IBAction func handleButtonPressed(sender:UIButton!)
 {

 switch sender.tag {

   let button = sender as! UIButton
   let view = button.superview!
   let cell = view.superview as! custom cell
  // cell.btn1  - will get here 
  //cell.btn2 - will get here
  // do based on what on button action hide or show
  case 0:
  print(sender.tag)

  case 1:
  print(sender.tag)
  case 2:
  print(sender.tag)
  case 3:
  print(sender.tag)

    default:
    print("Tag was not found")
   }
 }

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 2021-06-23
    • 1970-01-01
    • 2020-12-23
    • 2012-01-30
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    相关资源
    最近更新 更多