1

I have one UILabel, and i want to fade the end of the string, that is going to be out of bounds. What is the better solution for this? Should i calculate the width of the label, compare it with the string width, and if string width is bigger than label's, i should fade last two letters? How exactly should i do that? I hope it will be easy. Please write your solutions. Thanks! I prefer to use this method for calculating the width:

CGRect labelRect = [text
                    boundingRectWithSize:labelSize
                    options:NSStringDrawingUsesLineFragmentOrigin
                    attributes:@{
                     NSFontAttributeName : [UIFont systemFontOfSize:14]
                    }
                    context:nil];
mikezs
  • 301
  • 1
  • 7
  • 16
  • 1
    briefly, masking the view with a gradient image and set `clipToBounds` to true. – holex Jun 23 '14 at 12:01
  • I think you are looking for "http://stackoverflow.com/questions/3786528/iphone-ipad-how-exactly-use-nsattributedstring" – Yogendra Jun 23 '14 at 12:06

4 Answers4

4

You can fade one line label using 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;

Sample fade label

avdyushin
  • 1,782
  • 15
  • 19
3

Swift 4.0 example:

    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

result:

result

pchelnikov
  • 281
  • 3
  • 6
0

I've found the answer - i should use GTMFadeTruncatingLabelTest class from google

Neeraj Kumar
  • 739
  • 2
  • 16
  • 30
mikezs
  • 301
  • 1
  • 7
  • 16
0

Works only from layoutSubviews() method

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
}