【问题标题】:Create several buttons创建多个按钮
【发布时间】:2017-08-17 09:17:50
【问题描述】:

我想在ViewController 中创建 10 个按钮。这些按钮将用户移动到下一个ViewController。如果我使用情节提要,是否必须创建 10 个按钮,还是有更简单的方法来解决问题?

还应满足以下条件:

  • 我的单元格按钮不会是灰色或其他颜色。但我需要选择我的按钮并更改颜色。
  • 如果我使用 tableView 并按下按钮,选定的单元格将填充为灰色。我只想选择按钮。 (Tableview 不应显示灰色以供选择)

【问题讨论】:

  • 你想要一些特殊的网格吗?您可以在代码中创建这些按钮。
  • 你可以使用 UIColletionView 或 UITableview ,你需要决定哪个最适合你
  • @Phyber 我知道,但我想为不同的屏幕使用自动布局
  • 您也可以在代码中使用自动布局。
  • @Dev_Tandel 提到你可以使用 UICollectionView、UITableView 或者你可以使用 UIStackView。

标签: ios swift uitableview button


【解决方案1】:

这是解决您问题的示例代码(它根据您的要求工作,只需复制并粘贴到您的视图控制器中)

import UIKit

class ViewController2: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tblTable: UITableView!

    var buttonTitles = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]


    override func viewDidLoad() {
        super.viewDidLoad()
        tblTable.delegate = self
        tblTable.dataSource = self
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return buttonTitles.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "buttoncell") as! ButtonCell

      let buttonTitle: String = buttonTitles[indexPath.row]
      cell.btnButton.setTitle(buttonTitle, for: .normal)
      cell.btnButton.tag = indexPath.row
      cell.btnButton.addTarget(self, action: #selector(self.buttonClick(button:)), for: .touchUpInside)
      cell.selectionStyle = .none
      return cell
   }

   @objc func buttonClick(button: UIButton) -> Void {
    print("btnButton clicked at index - \(button.tag)")
    button.isSelected = !button.isSelected

    if button.isSelected {
        button.backgroundColor = UIColor.green
    } else {
        button.backgroundColor = UIColor.yellow
    }
  }

}


class ButtonCell: UITableViewCell {

    @IBOutlet var btnButton: UIButton!

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        if selected {
            btnButton.backgroundColor = UIColor.green
        } else {
            btnButton.backgroundColor = UIColor.yellow
        }

    }

    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)

        if highlighted {
            btnButton.backgroundColor = UIColor.green
        } else {
            btnButton.backgroundColor = UIColor.yellow
        }
    }
}


带有表格视图和单元格界面设计的故事板布局快照

这是模拟器中的结果(按钮的工作行为)

我认为,这足以解决您的问题。

【讨论】:

猜你喜欢
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2021-04-18
相关资源
最近更新 更多