我需要改变UIView的颜色然后点击它。我怎么能这样做?
P.S。对不起我的英文
答案 0 :(得分:1)
这是步骤。
这是视图控制器的完整代码
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.
}
}
的项目网址
答案 1 :(得分:0)
//首先转到身份检查器并在视图上设置“启用用户交互” //然后将其放在viewDidLoad方法中(将myExampleView更改为您的视图名称)
let tapChangeColor = UITapGestureRecognizer(target: self, action: #selector(changeColor))
self.myExampleView.addGestureRecognizer(tapChangeColor)
//将此方法放在ViewController类中的某个位置:
func changeColor() {
self.myExampleView.backgroundColor=UIColor.blue
}