iOS
Swift

タップエリアを広げる(extension版)

More than 1 year has passed since last update.

UIButtonを継承してpointInsideを上書きするというやり方を知っていたんだけど、いちいち継承しないといけなくてダルいなぁと思っていたのでちょっと頑張ってみた。

import UIKit
import ObjectiveC

extension UIButton {
  private struct AssociatedKey {
    static var tappableInsets = UInt()
  }

  var tappableInsets: UIEdgeInsets {
    get {
      let value = objc_getAssociatedObject(self, &AssociatedKey.tappableInsets) as? NSValue
      return value?.UIEdgeInsetsValue() ?? UIEdgeInsetsZero
    }

    set {
      objc_setAssociatedObject(self, &AssociatedKey.tappableInsets, NSValue(UIEdgeInsets: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
  }

  override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let insets = tappableInsets

    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)
    return CGRectContainsPoint(rect, point)
  }
}

黒魔術…。