閲覧ありがとうございます。
tableView上でカスタムセルを使うのにあたり「.swift」の新しいファイルを作りそこにカスタムセルの中身をコードで書いています。
カスタムセルの中に配置したボタンがタップされたら、tableViewのindexPath.rowを使用した処理を書きたいのですが、どうすればよいか検討もつきません。
分かる方がいらっしゃいましたら教えてください。
Swift
1 2// カスタムセルのクラス 3class CustomCell: UITableViewCell { 4 5 // ボタンを作成 6 var botton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 30)) 7 8 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { 9 super.init(style: style, reuseIdentifier: reuseIdentifier) 10 11 // ボタンを貼る 12 botton.setTitle("Botton", for: .normal) 13 botton.setTitleColor(.black, for: .normal) 14 botton.addTarget(self, action: #selector(sample), for: .touchUpInside) 15 contentView.addSubview(botton) 16 } 17 18 @objc func sample() { 19 // ここにindexPath.rowを使った処理を書きたいです 20 print("ここにindexPath.rowを使った処理を書きたいです") 21 } 22 23 required init?(coder aDecoder: NSCoder) { 24 fatalError("init(coder:) has not been implemented") 25 } 26 27 override func awakeFromNib() { 28 super.awakeFromNib() 29 // Initialization code 30 } 31 32 override func setSelected(_ selected: Bool, animated: Bool) { 33 super.setSelected(selected, animated: animated) 34 35 // Configure the view for the selected state 36 } 37} 38 39class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 40 41 42 override func viewDidLoad() { 43 super.viewDidLoad() 44 45 // tableViewを表示 46 let myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 200, height: 400), style: .plain) 47 myTableView.rowHeight = 45 48 myTableView.delegate = self 49 myTableView.dataSource = self 50 myTableView.allowsSelection = false 51 myTableView.register(CustomCell.self, forCellReuseIdentifier: NSStringFromClass(CustomCell.self)) 52 53 view.addSubview(myTableView) 54 55 } 56 57 func numberOfSections(in tableView: UITableView) -> Int { 58 return 1 59 } 60 61 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 62 return 25 63 } 64 65 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 66 let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(CustomCell.self), for: indexPath) as! CustomCell 67 68 return cell 69 } 70} 71
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/11 09:09
2019/04/12 02:53