質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1168閲覧

カスタムセルで作成したボタンを押下出来ない

Ka_ya_

総合スコア31

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2020/08/01 05:05

質問失礼します。

コードのみでテーブルビューを作成したいです。

ボタンのあるカスタムセルクラスを使用したいのですが、
下記の様に記載したところ、ボタンを押下しても反応がありません。

これは何が原因なのでしょうか。

どなたかご教授いただけますと嬉しいです。
よろしくお願い致します。

Swift

1import UIKit 2 3class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 4 5 //スクリーンサイズ 6 var screenSize = CGSize() 7 8 ///背景画像 9 let imageView :UIImageView = { 10 11 let image:UIImage = UIImage(named:"noimage")! 12 let iv = UIImageView(image:image) 13 iv.contentMode = .scaleAspectFill 14 iv.frame = UIScreen.main.bounds 15 return iv 16 }() 17 18 ///テーブルビュー 19 let tableView :UITableView = { 20 21 let tv = UITableView() 22 tv.backgroundColor = .clear 23 tv.separatorStyle = .none 24 //カスタムセルを登録する 25 tv.register(CustomCell.self, forCellReuseIdentifier: "customCell") 26 tv.translatesAutoresizingMaskIntoConstraints = false 27 return tv 28 }() 29 30 //ヘッダー 31 var headerView = UIView() 32 33 override func viewDidLoad() { 34 super.viewDidLoad() 35 36 //スクリーンサイズの取得 37 screenSize = self.view.frame.size 38 39 //背景画像の設定 40 self.view.addSubview(imageView) 41 42 //ヘッダービューを設定 43 headerView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height / 6) 44 headerView.backgroundColor = UIColor(red: 88 / 255, green: 0 / 255, blue: 88 / 255, alpha: 1.0) 45 view.addSubview(headerView) 46 47 //テーブルビューを設定 48 view.addSubview(tableView) 49 50 tableView.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true 51 tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true 52 tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true 53 tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true 54 55 tableView.delegate = self 56 tableView.dataSource = self 57 } 58 59 //セルの個数 60 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 61 return 5 62 } 63 64 //セルの高さ 65 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 66 return (screenSize.height - headerView.frame.size.height) / 8 67 } 68 69 //セルの設定 70 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 71 ///カスタムセルを使用する 72 let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell 73 74 return cell 75 } 76} 77

Swift

1import UIKit 2 3class CustomCell: UITableViewCell { 4 5 ///セル背景画像 6 let bgImageView :UIImageView = { 7 8 let image:UIImage = UIImage(named:"noimage")! 9 let iv = UIImageView(image:image) 10 iv.backgroundColor = .clear 11 iv.translatesAutoresizingMaskIntoConstraints = false 12 return iv 13 }() 14 15 ///コメントラベル 16 let commentLabel: UILabel = { 17 let label = UILabel() 18 label.font = UIFont.systemFont(ofSize: 18) 19 label.textColor = UIColor.black 20 label.textAlignment = .center 21 label.text = "テスト" 22 label.translatesAutoresizingMaskIntoConstraints = false 23 return label 24 }() 25 26 ///ボタン・ラベル格納用スタックビュー 27 let stackView :UIStackView = { 28 let sv: UIStackView = UIStackView() 29 sv.distribution = .equalSpacing 30 sv.axis = .horizontal 31 sv.translatesAutoresizingMaskIntoConstraints = false 32 return sv 33 }() 34 35 //ボタン 36 var button :UIButton = { 37 let btn = UIButton() 38 btn.backgroundColor = .red 39 btn.translatesAutoresizingMaskIntoConstraints = false 40 btn.addTarget(self, action: #selector(CustomCell.tap(_:)), for: .touchUpInside) 41 return btn 42 }() 43 44 ///ラベル 45 let label: UILabel = { 46 let label = UILabel() 47 label.font = UIFont.systemFont(ofSize: 12) 48 label.textColor = UIColor.black 49 label.textAlignment = .center 50 label.adjustsFontSizeToFitWidth = true 51 label.translatesAutoresizingMaskIntoConstraints = false 52 label.text = "テスト" 53 return label 54 }() 55 56 //ここにUI部品を追加していく 57 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { 58 super.init(style: style, reuseIdentifier: reuseIdentifier) 59 60 //背景の設定 61 addSubview(bgImageView) 62 63 bgImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true 64 bgImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true 65 bgImageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true 66 bgImageView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true 67 68 //コメントの設定 69 addSubview(commentLabel) 70 71 commentLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true 72 commentLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true 73 commentLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true 74 commentLabel.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.25).isActive = true 75 76 //スタックビュー 77 addSubview(stackView) 78 79 stackView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true 80 stackView.topAnchor.constraint(equalTo: commentLabel.bottomAnchor, constant: 10).isActive = true 81 stackView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true 82 stackView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1/3).isActive = true 83 84 //ボタンの設定 85 stackView.addArrangedSubview(button) 86 87 button.widthAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true 88 button.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true 89 90 //ラベルの設定 91 stackView.addArrangedSubview(label) 92 93 label.widthAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 0.2).isActive = true 94 label.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true 95 } 96 97 required init?(coder: NSCoder) { 98 fatalError("init(coder:) has not been implemented") 99 } 100 101 //押下時の挙動 102 @objc func tap(_ sender: Any) { 103//ボタンを押下してもプリントされない 104 print("タップ") 105 } 106}

イメージ説明

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

初期化クロージャ(Initialization closure)の中ではselfは使えません(未定のため)。

なので、

var button :UIButton = { let btn = UIButton() btn.backgroundColor = .red btn.translatesAutoresizingMaskIntoConstraints = false // btn.addTarget(self, action: #selector(CustomCell.tap(_:)), for: .touchUpInside) return btn }()

という具合にコメントアウトなり削除するなりしたあと、イニシャライザの中で

Swift

1 button.widthAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true 2 button.heightAnchor.constraint(equalTo: stackView.heightAnchor).isActive = true 3 button.addTarget(self, action: #selector(CustomCell.tap(_:)), for: .touchUpInside)

という感じでターゲットを追加したら想定通りに動くかと思います。

あるいは、lazy キーワードを使う方法もあるかと思います(遅延評価させる)。

Swift

1 lazy var button :UIButton = { 2 let btn = UIButton() 3 btn.backgroundColor = .red 4 btn.translatesAutoresizingMaskIntoConstraints = false 5 btn.addTarget(self, action: #selector(CustomCell.tap(_:)), for: .touchUpInside) 6 7 return btn 8 }()

この場合はイニシャライザで addTargetする必要はありません。

投稿2020/08/01 10:10

TsukubaDepot

総合スコア5086

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Ka_ya_

2020/08/01 10:34

TsukubaDepotさん、いつもご回答ありがとうございます。 初期化クロージャの中ではselfが使用出来ないのですね…! lazyの使用方法も記載いただき、とても勉強になります。 お陰様で、無事にボタンを押下出来る様になりました^^ 丁寧にご回答いただき、本当にありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問