[英]how can I click button inside UI table view cell (custom cell ) and then goto other viewcontroller
[英]How can I add a button in a custom cell?
我正在從XIB
文件制作一個自定義單元格並在我的tableView
實現,我能夠實現自定義單元格中的文本,但是如何為按鈕實現相同的功能並接收觸摸呢?
這是我寫的代碼:
struct cellData {
let cell : Int!
let text : String!
let button = UIButton()
}
var arrayOfData = [cellData]()
override func viewDidLoad() {
super.viewDidLoad()
arrayOfData = [cellData(cell : 1, text: "ahfhasdf", button: button)]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if arrayOfData[indexPath.row].cell==1{
let cell=Bundle.main.loadNibNamed("CustomTableViewCell1", owner: self, options: nil)?.first as! CustomTableViewCell1
cell.label1.text=arrayOfData[indexPath.row].text
cell.pillImage.currentImage=arrayOfData[indexPath].pillImage
return cell
}
我的pill
是CustomTableViewCell1
中的按鈕,我想要在我的單元格中以及按下按鈕時如何操作? 請幫忙。
這與您提出的問題有所不同,但我相信您正在尋找類似的東西。 我希望代碼和評論能夠說明問題。
// My cell from xib (storyboard)
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var button: UIButton!
@IBOutlet weak var cellImageView: UIImageView!
@IBOutlet weak var label: UILabel!
}
// My view controlle from xib (storyboard)
class MyViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
fileprivate var dataSource: [CellData] = [CellData]()
override func viewDidLoad() {
super.viewDidLoad()
dataSource = [CellData(index: 0, title: "First cell", image: nil, target: self, selector: #selector(firstCellPressed)),
CellData(index: 1, title: "Another cell", image: nil, target: self, selector: #selector(anyOtherCellPressed))]
tableView.reloadData()
}
@objc private func firstCellPressed() {
print("First cell pressed")
}
@objc private func anyOtherCellPressed(sender: UIButton) {
print("Cell at row \(sender.tag) pressed")
}
}
fileprivate extension MyViewController {
struct CellData {
let index: Int
let title: String?
let image: UIImage?
let target: Any?
let selector: Selector
}
}
extension MyViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCellIdentifier", for: indexPath) as! MyTableViewCell // Dequeue cell
let source = dataSource[indexPath.row] // Get the source object
cell.button.tag = indexPath.row // Assign tag so we can use it in the button action method
// Assign target and selector if it exists
if let target = source.target {
cell.button.addTarget(target, action: source.selector, for: .touchUpInside)
}
cell.cellImageView.image = source.image // Assign image
cell.label.text = source.title // Assign title
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
}
這仍然遠不是我想做的事情,而是隨意嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.