在不同的viewController上使用tapGesture更改图像颜色

时间:2017-08-24 18:08:31

标签: ios swift uiimageview uitapgesturerecognizer

当我点击另一个viewController wCircle上的UIImageView时,我试图让UIImageView rDot变为红色。问题是,当我点击rDot时,我收到错误Thread 1: EXC_BAD_INSTRUCTION (code = EXC_I386_INVOP subcode = 0x0)我使wCircle成为一个全局变量,因此可以在另一个viewController中找到它。

第一个viewController

weak var wCircle: UIImageView!

class SecondViewController: UIViewController {
    @IBOutlet weak var wCircle: UIImageView!
}

第二个viewController

class ProgressViewController: UIViewController {   
    @IBOutlet weak var rDot: UIImageView!                   
    override func viewDidLoad() {
        super.viewDidLoad()               
        rDot.isUserInteractionEnabled = true            
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rdotimageTapped(tapGestureRecognizer:)))            
        rDot.addGestureRecognizer(tapGestureRecognizer)          
    }    

    func rdotimageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
        wCircle.image = wCircle.image!.withRenderingMode(.alwaysTemplate) //error on this line
        wCircle.tintColor = UIColor.red     
    }
}

2 个答案:

答案 0 :(得分:0)

你的代码没有组织,没有任何表示

更改此行代码

替换weak var wCircle: UIImageView!

weak var wCircle = UIImageView()

和这个

func rdotimageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
    wCircle?.image = whiteDot.image!.withRenderingMode(.alwaysTemplate) //error on this line
    wCircle?.tintColor = UIColor.red
}

答案 1 :(得分:0)

wCircle是弱变量,它是可选值。所以当你从其他类调用它时,它不可选。也使它成为强变量