我正在尝试设置手势识别器(UITapGestureRecognizer),通过单击一次并将视图颜色更改为蓝色,然后在第二次单击中将其更改为黄色,然后再将其更改为默认颜色红色。
class ViewController: UIViewController {
var squarView:UIView!;
var squarIsBlue:Bool = true;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
squarView = UIView(frame: CGRect(x: 130, y: 130, width: 150, height: 150));
squarView.backgroundColor = UIColor.redColor();
var squarTap = UITapGestureRecognizer(target: self, action: "tapMe:");
squarView.addGestureRecognizer(squarTap);
squarView.userInteractionEnabled = true;
view.addSubview(squarView);
}
func tapMe(sender:UIGestureRecognizer){
squarView.backgroundColor = UIColor.blueColor();
if (squarIsBlue == false){
squarView.backgroundColor = UIColor.yellowColor();
if(squarIsBlue == true){
squarView.backgroundColor = UIColor.redColor();
}
squarIsBlue = true
}
squarIsBlue = false;
println("Squar Tapped!!!");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我做错了什么?
答案 0 :(得分:2)
你在tapMe逻辑中有错误。在这种特殊情况下,最好使用Integer变量而不是布尔值,因为你有3种状态(红色,蓝色,黄色)...
试试这个:
import UIKit
class ViewController: UIViewController {
private var tapGesture : UITapGestureRecognizer!
private var childView : UIView!
private let colorPalette = [UIColor.redColor(),UIColor.blueColor(),UIColor.yellowColor()]
private var currentColorIdx = 0 {
didSet{
childView.backgroundColor = colorPalette[currentColorIdx]
}
}
override func viewDidLoad() {
super.viewDidLoad()
tapGesture = UITapGestureRecognizer(target: self, action: "didTap:")
childView = UIView(frame: CGRect(x: 130, y: 130, width: 150, height: 150))
childView.backgroundColor = colorPalette.first
self.view.addSubview(childView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
childView.addGestureRecognizer(self.tapGesture)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
childView.removeGestureRecognizer(self.tapGesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func didTap(gesture: UIGestureRecognizer){
currentColorIdx = (currentColorIdx + 1 ) % colorPalette.count
}
}
答案 1 :(得分:0)
你可以将你的squarIsBlue变量设置为int而不是Bool,设置颜色,如0 =红色(默认),1 =蓝色,2 =黄色,
现在,在viewdidLoad中,设置类似
的内容squarIsBlue=0
squarView.backgroundColor = UIColor.redColor();
更改您的点击方法,如
func tapMe(sender:UIGestureRecognizer){
squarView.backgroundColor = UIColor.blueColor();
if (squarIsBlue == 0){
squarView.backgroundColor = UIColor.blueColor();
squarIsBlue=1;
else if (squarIsBlue == 1) {
squarView.backgroundColor = UIColor.yellowColor();
squarIsBlue =2
}
else if (squarIsBlue==2) {
squarView.backgroundColor = UIColor.redColor();
squarIsBlue=0;
}
println("Squar Tapped!!!");
}
希望,这有助于你,
HTH,享受编码!!