Reputation: 17132
I have a table view with a label array and a UIView, with a UIImage array
var menuItems = ["News", "Programm"]
var currentItem = "News"
var menuImages: [UIImage] = [UIImage(named: "news.png")!, UIImage(named: "programm_100.png")!]
The text and its color of the label is set by:
cell.titleLabel.text = menuItems[indexPath.row]
cell.titleLabel.textColor = (menuItems[indexPath.row] == currentItem) ? UIColor.whiteColor() : UIColor.grayColor()
Now I want the Images to appear a bit grey, too.
I've tried to set it with cell.titlePicture.alpha
.
How can I set UIView's alpha denericly depending on the current item?
Upvotes: 2
Views: 2930
Reputation: 3489
You can use an Extension. Just create a new Swift file and implement this:
import UIKit
extension UIImage{
func alpha(value:CGFloat)->UIImage
{
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
let ctx = UIGraphicsGetCurrentContext();
let area = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSetBlendMode(ctx, CGBlendMode.Normal);
CGContextSetAlpha(ctx, value);
CGContextDrawImage(ctx, area, self.CGImage);
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
}
Then apply it when setting your image:
UIImage(named: "news.png").alpha(0.5)
Upvotes: 3
Reputation: 42449
Assuming titlePicture
is a UIImageView
, you can edit the alpha of it directly:
cell.titlePicture.alpha = (menuItems[indexPath.row] == currentItem) ? 0.6 : 1.0
Tweak the alpha values to your liking. Example output:
alpha = 1.0:
alpha = 0.6:
Upvotes: 3