【问题标题】:Objective C - Append ellipsis to a UILabel that is centrally aligned, but don't move text目标 C - 将省略号附加到居中对齐但不移动文本的 UILabel
【发布时间】:2015-05-01 20:16:30
【问题描述】:

我有一个宽度接近 100% 的 UILabel。文本居中对齐。

我有一些代码要附加或以其他方式演练省略号的添加。

但是,这会导致 UILabel 在动画发生时移动的问题。这是因为文本居中对齐。

我希望我的代码添加或以其他方式更新省略号,但不“移动” UILabel。

如果可以的话,我不想添加另一个标签,但如果这是唯一的解决方案,那就太酷了。

代码如下;

// This is a method inside a custom UILabel subclass
- (void)startProgressAnimationWithInterval:(NSTimeInterval)interval
{
    self.isAnimatingProgress = YES;

    NSString *singleDot = @".";
    NSString *doubleDot = @"..";
    NSString *tripleDot = @"...";

    if (![self.text hasSuffix:tripleDot]) {
        self.text = [self.text stringByAppendingString:tripleDot];
    }

    self.progressTimer = [NSTimer vic_scheduledTimerWithTimeInterval:interval userInfo:nil action:^(NSTimer *timer, NSInteger repeatIndex) {
        if ([self.text hasSuffix:tripleDot]) {
            self.text = [self.text stringByReplacingOccurrencesOfString:tripleDot withString:singleDot];
        }
        else if ([self.text hasSuffix:doubleDot]) {
            self.text = [self.text stringByReplacingOccurrencesOfString:doubleDot withString:tripleDot];
        }
        else {
            self.text = [self.text stringByReplacingOccurrencesOfString:singleDot withString:doubleDot];
        }
    }];
}

【问题讨论】:

    标签: objective-c text uilabel text-alignment


    【解决方案1】:

    有很多方法可以解决这个问题。例如,不是更改文本,而是将文本设置为包含省略号,然后只需将可变数量的椭圆点的字体颜色设置为标签的attributedText 的清晰颜色:

    - (void)handleTimer:(NSTimer *)timer {
        if (++self.dotsToShow >= 4) self.dotsToShow = 0;  // an integer state that rotates 0, 1, 2, 3 and then repeats
    
        NSInteger dotsToHide = 3 - self.dotsToShow;
    
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.label.text];
        if (dotsToHide > 0) {
            [string setAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} range:NSMakeRange(string.length - dotsToHide, dotsToHide)];
        }
        self.label.attributedText = string;
    }
    

    【讨论】:

    • 这听起来是一个比制作新标签更好的解决方案。我会试试看 !不过,我的背景不可信;它并不总是像纯色,但我会尝试它
    • 是的,我将椭圆设置为透明,所以无论你的背景是什么,它都会显示出来。
    猜你喜欢
    • 2011-08-09
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多