在UIVIew的TopLeft创建UILabel并直接向下动画?

时间:2016-05-25 22:01:21

标签: swift

我已经在这个新游戏上工作了几个月了,遇到了我无法解决的问题!

所以基本上我在UIViewController的右上角创建了一个“状态部分”。在此“状态部分”中,将显示UILabels状态更新为Strings。这些UILabels会出现在UIView的最左上方,并且会慢慢向下并且同时丢失Alpha。一旦到达底部,它就会消失。

我做了什么?

因此,在目前为止您可以在代码中看到我已经能够在随机位置创建UILabel,但出于某种原因,UILabels会在屏幕外生成。

enter image description here

代码

func createStatus() {


        let viewWidth = self.statusView.frame.width
        let viewHeight = self.statusView.frame.width

        let randomX = CGFloat(viewWidth / 2)
        let randomY = CGFloat(arc4random_uniform(UInt32(viewHeight)) + 50)


        let frame = self.statusView.frame.origin

        let status = UILabel(frame: CGRect(origin: CGPoint(x: CGFloat(viewWidth / 4) - 20, y: CGFloat(viewHeight - viewHeight) + 10), size: CGSize(width: 200.0, height: 50.0)))

        status.text = "This is a status"
        status.textColor = UIColor.redColor()
        status.alpha = 1
        self.statusView.addSubview(status)
        print("Status made")
        UIView.animateWithDuration(2) {
            status.center = frame
            status.alpha = 0

        }

    }

我添加了问题的图像和UIView statusView。我在左上角制作UILabel时遇到了麻烦,我在下面尝试了这个代码,它甚至没有“生成”屏幕上的UILabel。

let frame = self.statusView.frame.origin
CGPoint topLeft = CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame));

1 个答案:

答案 0 :(得分:2)

func createStatus() {


    let viewWidth = self.statusView.frame.width
    let viewHeight = self.statusView.frame.width

    //Why are these here?
    let randomX = CGFloat(viewWidth / 2)
    let randomY = CGFloat(arc4random_uniform(UInt32(viewHeight)) + 50)


    let origin = CGPointZero//Origins are relative to superview, so top left would be (0, 0)

    //Renamed status to statusLabel so that we know its a label and not a model object
    let statusLabel = UILabel(frame: CGRect(origin: origin, size: CGSize(width: 200.0, height: 50.0)))

    statusLabel.text = "This is a status"
    statusLabel.textColor = UIColor.redColor()
    statusLabel.alpha = 1
    self.statusView.addSubview(statusLabel)
    print("Status made")
    UIView.animateWithDuration(2) {
        //Animate the origin instead of center position. 
        //The origin will be the height of the statusView - the height of your label. x stays 0 to keep it along left edge.
        statusLabel.frame.origin = CGPoint(x: 0, y: self.statusView.frame.height - statusLabel.frame.height )
        statusLabel.alpha = 0

    }, { (completed) in
        if completed {
           //If statusLabel doesn't have a superView it will be dealloc after the function goes out of scope. So remove it from superview after animaion is complete and ARC takes care of it.
           statusLabel.removeFromSuperview()
        }

    }

}