我正在处理一个应用程序,该应用程序将从四个图像开始,最终会有更多图像添加到屏幕上但是现在我想弄清楚如何让应用程序随机选择一个每次UIImageView并将alpha设置为0.7,其余为1.0。我尝试了不同的方法让它发挥作用,但它似乎并不好看。我怎么能用我已经拥有的代码来做这个呢?我怎么能告诉他们找到了较低的alpha图像?
func randomCGFloat() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
extension UIColor {
static func randomColor() -> UIColor {
let r = randomCGFloat()
let g = randomCGFloat()
let b = randomCGFloat()
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
}
class ViewController: UIViewController {
@IBOutlet var image1: UIImageView?
@IBOutlet var image2: UIImageView?
@IBOutlet var image3: UIImageView?
@IBOutlet var image4: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let getColor = UIColor.randomColor()
self.image1?.backgroundColor = getColor
self.image2?.backgroundColor = getColor
self.image3?.backgroundColor = getColor
self.image4?.backgroundColor = getColor
}
答案 0 :(得分:0)
如果您需要所有图片的alpha值为1.0且只有alpha值为0.7,我建议如下:
首先在viewDidLoad()
的数组中获取所有图像,然后随机选择一个元素并应用0.7的alpha值(其他的默认alpha值为1.0)。
然后,您可以为每个imageViews添加一个点击识别器,并检查被调用的方法以查看alpha是否为0.7
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let getColor = UIColor.randomColor()
self.image1?.backgroundColor = getColor
self.image2?.backgroundColor = getColor
self.image3?.backgroundColor = getColor
self.image4?.backgroundColor = getColor
var imageViewsArray: [UIImageView] = [image1, image2, image3, image4]
var randomIndex = Int(arc4random()) % Int(imageViewsArray.count)
imageViewsArray[randomIndex].alpha = 0.7
for imageView in imageViewsArray {
imageView.userInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action:"imageTapped:")
imageView.addGestureRecognizer(tapRecognizer)
}
}
func imageTapped(gestureRecognizer: UITapGestureRecognizer) {
let tappedImageView = gestureRecognizer.view!
if tappedImageView.alpha == 0.7 {
// Success
}
}