我有一个带有标签数组的表视图和带有UIImage数组的UIView
var menuItems = ["News", "Programm"]
var currentItem = "News"
var menuImages: [UIImage] = [UIImage(named: "news.png")!, UIImage(named: "programm_100.png")!]
标签的文字及其颜色由:
设定cell.titleLabel.text = menuItems[indexPath.row]
cell.titleLabel.textColor = (menuItems[indexPath.row] == currentItem) ? UIColor.whiteColor() : UIColor.grayColor()
现在我希望图像看起来有点灰色。
我试图用cell.titlePicture.alpha
设置它。
如何根据当前项目设置UIView的alpha?
答案 0 :(得分:1)
假设titlePicture
是UIImageView
,您可以直接编辑它的alpha:
cell.titlePicture.alpha = (menuItems[indexPath.row] == currentItem) ? 0.6 : 1.0
根据自己的喜好调整alpha值。示例输出:
alpha = 1.0:
alpha = 0.6:
答案 1 :(得分:1)
您可以使用扩展程序。只需创建一个新的Swift文件并实现它:
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;
}
}
然后在设置图像时应用它:
UIImage(named: "news.png").alpha(0.5)