简体   繁体   English

如何更改UIview的边框颜色?

[英]How to change border color of UIview?

I would like to change the border color of a uiview when it's being pressed and return to the normal border color after release. 我想在按下uiview时更改其边框颜色,并在释放后返回到正常的边框颜色。 What is the best practise for doing this? 最佳做法是什么?

Something like the picture below: 如下图所示: 在此处输入图片说明

Don't use UITapGestureRecognizer . 不要使用UITapGestureRecognizer You can use UILongPressGestureRecognizer 您可以使用UILongPressGestureRecognizer

Code: 码:

   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")

    }

}

This will work perfectly. 这将完美地工作。

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
}

You can use UILongPressGestureRecognizer to change border color of UIView 您可以使用UILongPressGestureRecognizer更改UIView边框颜色

Add Gesture in viewDidLoad and in handleTap function you can change border color. 在viewDidLoad中添加Gesture,在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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM