答案 0 :(得分:5)
请勿使用 UITapGestureRecognizer 。您可以使用 UILongPressGestureRecognizer
代码:
override func viewDidLoad() {
super.viewDidLoad()
let view = UIView.init(frame: CGRect.init(x: 30, y: 200, width: 100, height: 40))
self.view.addSubview(view)
view.layer.borderColor = UIColor.black.cgColor
view.layer.borderWidth = 3
let tapForView = UILongPressGestureRecognizer(target: self, action: #selector(self.toChangeColor(recognizer:)))
tapForView.minimumPressDuration = 0.01
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapForView)
}
@objc func toChangeColor(recognizer:UILongPressGestureRecognizer)
{
// Apply logic for changing background color.
let view = recognizer.view
if recognizer.state == .began {
view?.layer.borderColor = UIColor.orange.cgColor
print("view began")
}
else if recognizer.state == .ended {
view?.layer.borderColor = UIColor.black.cgColor
print("view ended")
}
}
这将完美无缺。
答案 1 :(得分:0)
let tapForView = UITapGestureRecognizer(target: self, action: #selector(self.ToChangeColor(recognizer:)))
tapForView.numberOfTapsRequired = 1
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapForView)
@objc func ToChangeColor(recognizer:UITapGestureRecognizer)
{
// Apply logic for changing background color
}
答案 2 :(得分:0)
您可以使用UILongPressGestureRecognizer
更改UIView
在viewDidLoad和handleTap函数中添加手势,您可以更改边框颜色。
override func viewDidLoad() {
super.viewDidLoad()
let tap = UILongPressGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
customeview.addGestureRecognizer(tap)
}
@objc func handleTap(_ sender: UILongPressGestureRecognizer) {
print("Hello World")
if sender.state == .began
{
customeview.layer.borderColor = UIColor.yellow.cgColor
customeview.layer.borderWidth = 3
}
else if sender.state == .ended
{
customeview.layer.borderColor = UIColor.black.cgColor
customeview.layer.borderWidth = 3
}
}