滚动UILabel就像子视图中的选取框一样

Tus*_*oul 3 cocoa-touch objective-c uilabel ios

我在主视图中有一个UILabel文本 - "非常非常长的文本".适当的宽度是142,但我把它缩短到55.

基本上我想实现一个字幕类型滚动,所以我编写代码将其添加到子视图中并在该视图的边界内对其进行动画处理.

代码 -

    CGRect tempLblFrame = _lblLongText.frame;
    UIView *lblView = [[UIView alloc] initWithFrame:tempLblFrame];

    //Add label to UIView at 0,0 wrt to new UIView
    tempLblFrame.origin.x = 0;
    tempLblFrame.origin.y = 0;

    [_lblLongText setFrame:tempLblFrame];
    [_lblLongText removeFromSuperview];
    [lblView addSubview:_lblLongText];

    //SetClipToBounds so that if label moves out of bounds of its superview, it wont be displayed
    [lblView setClipsToBounds:YES];
    [lblView setBackgroundColor:[UIColor cyanColor]];
    [self.view addSubview:lblView];
Run Code Online (Sandbox Code Playgroud)

在此之后,我在模拟器上得到了这个输出 - > 在此输入图像描述

当我使用此代码尝试动画时出现问题 -

    tempLblFrame.origin.x = -_lblLongText.intrinsicContentSize.width;        
    [UIView animateWithDuration:2.0 delay:1.0 options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         [_lblLongText setFrame:tempLblFrame];
                     }
                     completion:^(BOOL finished) {
                         NSLog(@"completed");
                     }];
Run Code Online (Sandbox Code Playgroud)

我希望我能看到整个"非常长的文本",而只是"非常......"从左到右滚动.

为了解决这个问题,我添加了一行代码 -

    //Add label to UIView at 0,0 wrt to new UIView
    tempLblFrame.origin.x = 0;
    tempLblFrame.origin.y = 0;

    tempLblFrame.size.width = _lblLongText.intrinsicContentSize.width; //THIS LINE WAS ADDED

    [_lblLongText setFrame:tempLblFrame];
    [_lblLongText removeFromSuperview];
    [lblView addSubview:_lblLongText];
Run Code Online (Sandbox Code Playgroud)

我认为全文将在新添加的UIView中设置,它会正确滚动.但是在模拟器中运行给了我这个 -

在此输入图像描述

而且,只有"非常......"从左向右滚动.

我究竟做错了什么?请帮忙!!

编辑

显然罪魁祸首是AutoLayout.

我不知道为什么,但是一旦我取消选中"使用Autolayout"来查看XIB中的视图,一切都按预期开始工作.设置tempLblFrame.origin.x = -_lblLongText.intrinsicContentSize.width; 滚动正常,滚动也正常.

对此有任何解释!!?

iLe*_*ner 5

这个问题可能是重复的.

尽管Charles Powell为MarqueeLabel编写了很好的代码片段,

另请看这个链接.

我希望这会对你有所帮助,并通过提供所需的输出来节省你的时间.