点击UIView并更改颜色本身

时间:2016-10-30 00:56:11

标签: uiview swift3

我需要改变UIView的颜色然后点击它。我怎么能这样做?

P.S。对不起我的英文

2 个答案:

答案 0 :(得分:1)

这是步骤。

  1. 将UIView拖到ViewController
  2. 然后为它创建一个IBOutlet。 (只需将连接拖到viewcontroller类)。
  3. 然后为它创建手势。
  4. 然后为它创建一个动作。
  5. 分配行动
  6. 这是视图控制器的完整代码

    import UIKit
    
    class ViewController: UIViewController {
    
    
        //Outlet Connection to your View
    
        @IBOutlet weak var myView: UIView!
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            myView.layer.borderColor = UIColor.black.cgColor
            myView.layer.borderWidth = 2
    
    
            let taptoColorGesture = UITapGestureRecognizer.init(target: self, action: #selector(ViewController.changeMyColor))
            myView.addGestureRecognizer(taptoColorGesture)
    
            // Do any additional setup after loading the view, typically from a nib.
        }
    
    
        func changeMyColor () {
    
            let colorR : Float = Float(Int(arc4random_uniform(255)))
            let colorG : Float = Float(arc4random_uniform(255))
            let colorB : Float = Float(arc4random_uniform(255))
    
            let themyColor = UIColor.init(colorLiteralRed: colorR/255, green: colorG/255, blue: colorB/255, alpha: 1.0)
    
            myView.backgroundColor = themyColor
    
           //this function creates random color each time
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
    }
    

    这是github Change the UIView Color on tap in Swift

    的项目网址

答案 1 :(得分:0)

//首先转到身份检查器并在视图上设置“启用用户交互” //然后将其放在viewDidLoad方法中(将myExampleView更改为您的视图名称)

let tapChangeColor = UITapGestureRecognizer(target: self, action: #selector(changeColor)) 
self.myExampleView.addGestureRecognizer(tapChangeColor)

//将此方法放在ViewController类中的某个位置:

func changeColor() {

self.myExampleView.backgroundColor=UIColor.blue

}