2016-08-22 67 views
1

我的屏幕上有幾個UIImageViews,如果其中一個被點擊,它必須改變他的顏色。正如我曾與UIView的同樣的問題,解決辦法是:Swift中UIImageView和UITapGestureRecognizer的交互

func viewTapped(recognizer:UITapGestureRecognizer) { 

    viewTouched = recognizer.view as UIView! 
    thisCard.backgroundColor = UIColor.orangeColor() 

} 

但我還沒有找到圖像視圖進行類似動作。你可以幫幫我嗎?

回答

1

你可以改變你的UIImageView S的tintColor

func imageViewTapped(recognizer:UITapGestureRecognizer) { 

    guard let imageView = recognizer.view as? UIImageView 
     else { return } 
    imageView.tintColor = UIColor.orangeColor() 

} 
+1

現在,它的工作原理。非常感謝! – Roman

0

UIImageView不工作? 如果不是,請檢查userInteractionEnabled

userInteractionEnabled設置爲true。

的UIImageView

public var userInteractionEnabled: Bool // default is NO 
+0

是的,它現在有效。第一個答案已修復它。謝謝! – Roman

0

創建圖像視圖的擴展

extension UIImage { 
    func tintWithColor(color:UIColor)->UIImage { 

     UIGraphicsBeginImageContext(self.size) 
     let context = UIGraphicsGetCurrentContext() 

     // flip the image 
     CGContextScaleCTM(context, 1.0, -1.0) 
     CGContextTranslateCTM(context, 0.0, -self.size.height) 

     // multiply blend mode 
     CGContextSetBlendMode(context, .Overlay) 

     let rect = CGRectMake(0, 0, self.size.width, self.size.height) 
     CGContextClipToMask(context, rect, self.CGImage) 
     color.setFill() 
     CGContextFillRect(context, rect) 

     // create uiimage 
     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return newImage 

    } 
} 

現在使用類似這樣的

yourImageView.image = yourImageView.image!.tintWithColor(UIColor.orangeColor()) 
相關問題