【问题标题】:Animate UILabel width with fixed center以固定中心为 UILabel 宽度设置动画
【发布时间】:2015-09-25 07:37:32
【问题描述】:

如何在保持视图居中的同时为宽度变化设置动画?

目前我这样做时,它不会从中心长出来。

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)

【问题讨论】:

    标签: swift uiview uilabel uianimation


    【解决方案1】:

    这对你有用。 您只需要为宽度和高度指定比例(默认为 1,这将无效)。这将为您的视图框架设置动画。

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

    如果你不想拉伸内容,你可以试试这个:

            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)
    

    【讨论】:

    • @EricD。抱歉,objective-c 代码。用 Swift 代码 sn-p 更新了我的答案。
    • 感谢@EricD。我不想拉伸内容,特别是如果我里面有文字。有没有办法真正改变宽度?
    • @bvallelunga 希望现在对您有所帮助。 :)
    • @bvallelunga 如果合适,请接受此作为答案。它会帮助其他人选择最好的。
    • 但是你不能在 Obj C 中为结构的一部分赋值。赋值给size 会给你一个错误。那么你如何在 Obj C 中做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 2016-06-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2013-01-15
    相关资源
    最近更新 更多