Animate UILabel width with fixed center

好久不见. 提交于 2020-01-24 12:46:05

问题


How to animate a change in width while keeping the view centered?

Currently when I do it, it doesn't grow from the center.

self.textLabel = UILabel()
self.textLabel.frame = CGRectMake(0, 0, Globals.voterTextLabel, Globals.voterTextLabel)
self.textLabel.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2)
self.textLabel.text = "VS"
self.textLabel.layer.cornerRadius = Globals.voterTextLabel/2
self.textLabel.layer.masksToBounds = true
self.textLabel.clipsToBounds = true
self.textLabel.backgroundColor = UIColor.whiteColor()
self.textLabel.textColor = Colors.voterTextLabel
self.textLabel.textAlignment = .Center
self.textLabel.autoresizingMask = .FlexibleWidth
self.view.addSubview(self.textLabel) 

 UIView.animateWithDuration(2, animations: {
    self.textLabel.frame.size.width = 150
    self.textLabel.center.x = self.view.frame.width/2
 }, completion: nil)

回答1:


This will work for you. You just need to give scale for width and height (default 1, which will have no effect). And this will animate your view's frame.

    UIView.animateWithDuration(2, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
        self.textLabel.transform=CGAffineTransformMakeScale(3, 1);
    }, completion: nil)

And if you don't want to stretch the content, than you may try this:

        UIView.animateWithDuration(2, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in

        var newWidth:CGFloat = 200.0;

        var oldWidth:CGFloat = self.textLabel.frame.width;

        var totalChangeWidth:CGFloat = newWidth - oldWidth;

        var newHeight:CGFloat = 200.0;

        var oldHeight:CGFloat = self.textLabel.frame.width;

        var totalChangeHeight:CGFloat = newHeight - oldHeight;

        self.textLabel.bounds.size = CGSizeMake(self.textLabel.frame.size.width + totalChangeWidth, self.textLabel.frame.size.height + totalChangeHeight);

        self.textLabel.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2)

    }, completion:nil)


来源:https://stackoverflow.com/questions/32777134/animate-uilabel-width-with-fixed-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!