点击更改视图颜色然后返回原始颜色

时间:2018-01-23 03:37:07

标签: ios swift uiview uitapgesturerecognizer

我正在尝试使用UITapGestureRecognizer在点击视图时更改UIView颜色,然后在点击UIView外部的空间时返回原始白色。我可以让UIView改变颜色,但我不能让它改回白色。

  // viewDidLoad
let tapGestureRegonizer = UITapGestureRecognizer(target: self, action: 
#selector(mortgagePenaltyVC.viewCellTapped(recognizer:)))
    tapGestureRegonizer.numberOfTapsRequired = 1
    mortgageLenerViewCell.addGestureRecognizer(tapGestureRegonizer)

@objc func viewCellTapped (recognizer: UITapGestureRecognizer){
    print("label Tapped")


    mortgageLenerViewCell.backgroundColor = UIColor.lightGray



    }

1 个答案:

答案 0 :(得分:0)

我认为您可以使用touchesBegan方法在视图之外触摸,如下所示

此代码适用于我......

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    guard let location = touch?.location(in: mortgageLenerViewCell) else { return }
    if !labelToClick.frame.contains(location) {
        print("Tapped outside the view")
        mortgageLenerViewCell.backgroundColor = UIColor.white
    }else {
        print("Tapped inside the view")
        mortgageLenerViewCell.backgroundColor = UIColor.lightGray
    }
}

此处labelToClick是您要点击的标签&amp; mortgageLenerViewCelllabelToClick

的超级视图

随意询问任何疑问......

谢谢。