我有一个UILabel
,我希望淡化字符串的结尾,这将超出界限。对此有什么更好的解决方案?
我应该计算标签的宽度,将其与字符串宽度进行比较,如果字符串宽度大于标签的宽度,我应该淡化最后两个字母?我到底应该怎么做?
我希望这很容易。请写下你的解决方案。谢谢!
我更喜欢使用这种方法来计算宽度:
CGRect labelRect = [text
boundingRectWithSize:labelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : [UIFont systemFontOfSize:14]
}
context:nil];
答案 0 :(得分:3)
您可以使用CAGradientLayer
CAGradientLayer *l = [CAGradientLayer layer];
l.frame = self.textLabel.bounds;
l.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor];
l.startPoint = CGPointMake(0.1f, 1.0f);
l.endPoint = CGPointMake(0.95f, 1.0f);
self.textLabel.layer.mask = l;
答案 1 :(得分:2)
Swift 4.0示例:
let gradient = CAGradientLayer()
gradient.frame = titleLabel.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.clear.cgColor]
gradient.startPoint = CGPoint(x: 0.1, y: 0.0)
gradient.endPoint = CGPoint(x: 0.95, y: 0.0)
label.lineBreakMode = .byClipping
label.layer.mask = gradient
结果:
答案 2 :(得分:0)
我找到了答案 - 我应该使用google中的GTMFadeTruncatingLabelTest类
答案 3 :(得分:0)
仅通过layoutSubviews()方法工作
override func layoutSubviews() {
super.layoutSubviews()
let maskLayer = CALayer()
maskLayer.frame = label.bounds
let gradientLayer = CAGradientLayer()
gradientLayer.frame = label.bounds
gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.7, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 0.95, y: 0.0)
maskLayer.addSublayer(gradientLayer)
label.layer.mask = maskLayer
}