0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

xibで設定したUITableViewCell内のUIButtonをタップするとEXC_BAD_ACCESS

Posted at

状況

UITableViewCell(xib)内のUIButtonをタップ範囲を広げたくて
以下を参考に、UIButtonのカスタムクラスを作成
【iOS】UIButtonのタップ領域だけを拡大する - Qiita

ExpandTappedAreaButton.swift
import UIKit
import Foundation

class ExpandTappedAreaButton: UIButton {
    var insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        var rect = bounds
        rect.origin.x -= insets.left
        rect.origin.y -= insets.top
        rect.size.width += insets.left + insets.right
        rect.size.height += insets.top + insets.bottom

        // 変更したView領域がタップ領域に含まれているかどうか
        return rect.contains(point)
    }
}

カスタムクラスのプロパティを参照しようとすると、Thread1:EXC_BAD_ACCESSが発生する。

HogeCell.swift
@IBOutlet weak var favoriteButton: ExpandTappedAreaButton! //ここでカスタムクラスを指定
    
override func awakeFromNib() {
    //UIButtonにも存在するプロパティ
    hugaButton.imageView?.contentMode = .scaleAspectFit
    hugaButton.setImage(UIImage(named: "hoge.png"), for: .normal)
    //カスタムクラスのプロパティを参照 -> Thread1:EXC_BAD_ACCESS
    hugaButton.insets = UIEdgeInsets(top: 0, left: 0, bottom: 40, right: 0)
}

解決策

  • UITableViewCellのxibファイルから該当するボタン(hugaButton)を選択
  • Custom ClassをExpandTappedAreaButton(今回の例だと)に変更

以上。

原因

  • おそらくカスタムクラスはIBOutletよりもxibを優先するので、
    Custom Classを設定しない場合、UIButtonとして認識する
  • insetsというプロパティはカスタムクラスにしかない(UIButtonにはない)のでクラッシュ

※「EXC_BAD_ACCESSは解放済みオブジェクトへのアクセス時に起こるので、どのオブジェクトにアクセスしてエラーを吐いているのかを調べてください。(一番上の参考文献より)」-> この辺きっちり調べられるようになりたい。

参考

Objective-C - UITableVIewのreloadDataでのエラー(フリーズ)のついて|teratail

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?