簡體   English   中英

如何更改UIview的邊框顏色?

[英]How to change border color of UIview?

我想在按下uiview時更改其邊框顏色,並在釋放后返回到正常的邊框顏色。 最佳做法是什么?

如下圖所示: 在此處輸入圖片說明

不要使用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")

    }

}

這將完美地工作。

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
}

您可以使用UILongPressGestureRecognizer更改UIView邊框顏色

在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