我想在 ViewController
中创建 10 个按钮。这些按钮将用户移动到下一个 ViewController
。如果我使用 Storyboard,我是否必须创建 10 个按钮,或者是否有更简单的方法来解决问题?
还应满足以下条件:
- 我进入单元格的按钮不会是灰色或其他颜色。但我需要我的按钮被选中并更改颜色。
- 如果我使用 tableView 并按下按钮,所选单元格将填充为灰色。我只想选择按钮。 (Tableview 不应显示灰色以供选择)
最佳答案
这是解决您问题的示例代码(它根据您的要求工作,只需复制并粘贴到您的 View Controller 中)
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
}
}
}
以及带有表格 View 和单元格界面设计的 Storyboard布局快照
这是模拟器中的结果(按钮的工作行为)
我想,这足以解决你的问题。
关于ios - 创建几个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45731132/