斯威夫特 3
//
// ViewController.swift
// test
//
// Created by David Seek on 9/29/16.
// Copyright © 2016 David Seek. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = MyButton(frame: CGRect(x: 200, y: 200, width: 100, height: 100))
button.backgroundColor = UIColor.white
button.addedTouchArea = 50 // any value you want
button.addTarget(self, action:#selector(self.action), for: .touchUpInside)
self.view.addSubview(button)
}
func action() {
print("touched")
}
}
class MyButton: UIButton {
var addedTouchArea = CGFloat(0)
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let newBound = CGRect(
x: self.bounds.origin.x - addedTouchArea,
y: self.bounds.origin.y - addedTouchArea,
width: self.bounds.width + 2 * addedTouchArea,
height: self.bounds.width + 2 * addedTouchArea
)
return newBound.contains(point)
}
}
您正在创建一个尺寸为 100x100 的 UIButton,而使用 .addedTouchArea,您将拥有一个 UIButton - 光学尺寸仍为 100x100,但触摸区域为 150x150。
Swift 2.X
class MyButton: UIButton {
var addedTouchArea = CGFloat(0)
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
let newBound = CGRect(
x: self.bounds.origin.x - addedTouchArea,
y: self.bounds.origin.y - addedTouchArea,
width: self.bounds.width + 2 * addedTouchArea,
height: self.bounds.width + 2 * addedTouchArea
)
return newBound.contains(point)
}
}
界面生成器
如果您确实使用InterfaceBuilder 设置了按钮,请将我们的UIButton 子类应用于您的按钮。
然后为按钮设置一个出口,f.e.命名按钮XY。并将buttonXY.addedTouchArea = 50 设置在viewDidLoad 内,f.e.
UITableViewCell
因为您要求UITableViewCell。它的工作原理完全相同。
在您的 ViewController 类中:
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") as! TableViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.myButton.addedTouchArea = 50 // any value you want
tableView.rowHeight = 200
return cell
}
}
在您的 Cell 类中:
class TableViewCell: UITableViewCell {
@IBOutlet weak var myButton: MyButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func myButtonAction(_ sender: AnyObject) {
print("touched")
}
}
唯一需要注意的是:插座被设置为UIButton 插座,即使我在InterfaceBuilder 中将其声明为 MyButton 的子类。我不得不手动将插座更改为MyButton! @IBOutlet weak var myButton: MyButton!