创建几个按钮

时间:2017-08-17 09:17:50

标签: ios swift uitableview button

我想在ViewController中创建10个按钮。这些按钮可将用户移至下一个ViewController。如果我使用故事板,我是否必须创建10个按钮或者是否有更简单的方法来解决问题?

它还应满足以下条件:

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

1 个答案:

答案 0 :(得分:2)

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

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
        }
    }
}


具有tableview和单元界面设计的故事板布局快照

enter image description here

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

enter image description here

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

相关问题