这是我的按钮:
import UIKit
class PassButton: UIButton {
var videoVC: VideoGameVC?
required init(isEnabled: Bool = false) {
super.init(frame: .zero)
self.isEnabled = true
self.addTarget(self, action: #selector(pressed(_:)), for: .touchUpInside)
let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: 70, height: 80))
imageViewBackground.image = UIImage(named: "pass_button")
imageViewBackground.contentMode = UIView.ContentMode.scaleAspectFill
addSubview(imageViewBackground)
sendSubviewToBack(imageViewBackground)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func pressed(_ sender: UIButton) {
print("presovan")
}
}
这就是我将其添加到另一个视图控制器的方法:
func configPassButton() {
passButton = PassButton()
guard let passButton = passButton else { return }
view.addSubview(passButton)
passButton.translatesAutoresizingMaskIntoConstraints = false
passButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
passButton.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 20).isActive = true
}
它按照我想要的方式显示,但是可点击的区域很小。只有左上角是可点击的,而且是一个非常小的角落(比如整个表面的 10%)。我怎样才能修复整个区域都是可点击的?
与其手动为背景图像添加子视图,不如使用按钮的 .setBackgroundImage() 属性。另外,为 ImageView 设置了框架大小,但除非我忽略了它,否则没有为按钮本身设置框架大小。这可能就是按钮的可点击区域与图像尺寸不完全对应的原因。
要修复,请删除这些设置背景图像的行:
let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: 70, height: 80))
imageViewBackground.image = UIImage(named: "pass_button")
imageViewBackground.contentMode = UIView.ContentMode.scaleAspectFill
addSubview(imageViewBackground)
sendSubviewToBack(imageViewBackground)
并将上面的行替换为这些行以设置按钮的背景图像、内容模式、宽度和高度:
self.setBackgroundImage(UIImage(named: "pass_button"), for: .normal)
self.layoutIfNeeded()
self.subviews.first?.contentMode = .scaleAspectFill
self.widthAnchor.constraint(equalToConstant: 70).isActive = true
self.heightAnchor.constraint(equalToConstant: 80).isActive = true
完成这些更改后,按钮应该可以完全点击。