我已经创建了一个自定义的UIControl,其中一个图像和一个标题垂直和水平对齐,一个位于另一个的顶部,应该充当UIButton。
问题是,当元素是touch inside时,当我调用addTarget()来添加一个操作时,该操作并不能很好地执行,只有在多次点击之后才能完成工作。
导致此问题的原因是什么?
谢谢。
下面是这个UIControl元素的类。
class CustomImageTitleButton: UIControl {
private var image : UIImageView = UIImageView()
private var title : UILabel = UILabel()
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
self.backgroundColor = PrimaryLightColor
self.layer.cornerRadius = 20
self.translatesAutoresizingMaskIntoConstraints = false
image.translatesAutoresizingMaskIntoConstraints = false
title.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(image)
self.addSubview(title)
image.contentMode = .scaleAspectFit
title.textAlignment = .center
title.font = title.font.withSize(24)
setupConstraints()
}
private func setupConstraints() {
NSLayoutConstraint.activate([
image.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20),
image.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20),
image.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5, constant: 0),
image.bottomAnchor.constraint(equalTo: self.centerYAnchor, constant: 8),
title.topAnchor.constraint(equalTo: self.centerYAnchor),
title.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 4),
title.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -4),
title.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
func setImage(image : UIImage?) {
self.image.image = image
}
func setTitle(title : String?) {
self.title.text = title
}
}下面是该操作的实现:
singlePlayerButton.addTarget(self, action: #selector(initSinglePlayerGame), for: .touchUpInside) // singlePlayerButton is the custom UIControl
@objc func initSinglePlayerGame() {
print("single player tapped")
let gameRoom : GameViewController = GameViewController()
gameRoom.modalPresentationStyle = .fullScreen
self.present(gameRoom, animated: true, completion: nil)
}编辑:
它看起来像UIControl管理用户交互,但不是一个简单的点击,它更像是一个“点击,拖动和释放”的动作。
发布于 2020-05-10 03:14:21
https://stackoverflow.com/questions/61700964
复制相似问题