UIView没有一个名为" inertia"

时间:2015-03-01 03:55:56

标签: ios swift uiview

我试图以编程方式创建一个按钮,在点击时淡出,更改文本,然后淡入。但是,当我尝试编写淡入淡出动画的代码时,我收到错误," '的UIView'没有名为' inertia'的成员当然,惯性是按钮的名称。

这是我创建按钮的代码,它位于viewDidLoad()函数中调用的函数中:

var inertia = UIButton.buttonWithType(UIButtonType.System) as UIButton
    inertia.frame = CGRectMake(firstView.frame.width/2-(inertia.frame.width/2), firstView.frame.height/10, firstView.frame.width, firstView.frame.height/10)
    inertia.frame = CGRectMake(firstView.frame.width/2-(inertia.frame.width/2), firstView.frame.height/10, firstView.frame.width, firstView.frame.height/10)
    inertia.setTitle("Newton's First Law of Motion", forState: UIControlState.Normal)
    inertia.addTarget(self, action: "tapped:", forControlEvents: .TouchUpInside)
    self.firstView.addSubview(inertia)

这是我到目前为止点击按钮时的代码行,其中发生错误:

UIView.animateWithDuration(0.4, animations: {self.firstView.inertia.alpha = 0})

我相信我在按钮创建中遗漏了一些内容,因为当我从故事板创建按钮的插座时,淡入淡出动画不会产生错误。

请帮我解决这个问题,因为我会经常使用它。此外,如果你能找到一种方法让我正确地创建按钮的框架,而不必宣布它两次也是有用的。

我尝试了什么(无济于事):

我已将: UIButton!放在var inertia

之后

我试过`UIView.animateWithduration(0.4,动画:{self.inertia.alpha = 0})

2 个答案:

答案 0 :(得分:1)

只是打破问题界限,特别是self.firstView.inertia.alpha。 Self显然是你所在的类实例。我假设你报告的错误和你的代码firstView是一个UIView。现在您已添加惯性作为firstView的子视图,但这不会在视图上创建名为inertia的属性。换句话说,没有firstView.inertia。 firstView有一个subviews属性,它是anyobject的数组。

换句话说,你创建的惯例和惯用的按钮现在位于数组firstView.subviews中的某个位置,但很难说取决于它有多少其他视图作为子视图。

你可以遍历子视图数组来找到你之前称之为惯性的按钮,但是保持对惯性的引用可能更简单。你可以把它变成你班上的一个属性(如果只有一个这样的按钮),并用

调用你的代码
UIView.animateWithDuration(0.4, animations: {self.inertia.alpha = 0})

答案 1 :(得分:0)

据我所知,您的代码看起来像这样:

class ViewController:UIViewController {
var firstView:UIView!



func tapped(button: UIButton) {
    UIView.animateWithDuration(0.4) { self.firstView.inertia.alpha = 0 }
}


override func viewDidLoad() {
    super.viewDidLoad()

    var inertia = UIButton.buttonWithType(UIButtonType.System) as UIButton
    inertia.frame = CGRectMake(firstView.frame.width/2-(inertia.frame.width/2), firstView.frame.height/10, firstView.frame.width, firstView.frame.height/10)
    inertia.frame = CGRectMake(firstView.frame.width/2-(inertia.frame.width/2), firstView.frame.height/10, firstView.frame.width, firstView.frame.height/10)
    inertia.setTitle("Newton's First Law of Motion", forState: UIControlState.Normal)
    inertia.addTarget(self, action: "tapped:", forControlEvents: .TouchUpInside)
    self.firstView.addSubview(inertia)
}

}

现在,您收到该错误,因为inerta未在类中声明为属性,您只能在函数中创建它。如果您想在tapped()中按下该按钮,则只需更改:

UIView.animateWithDuration(0.4) { self.firstView.inertia.alpha = 0 }
// To
UIView.animateWithDuration(0.4) { button.alpha = 0 } // When TouchUpInside the button will pass itself

或者你可以通过添加:

来使它成为一个主题
var inertia:UIButton! // Under class ...

在设置var时删除viewDidLoad