【问题标题】:iOS .addConstraint only works onceiOS .addConstraint 只工作一次
【发布时间】:2014-08-28 19:39:45
【问题描述】:

我正在为 iOS8 制作自定义键盘,并且在 Apple 开发人员文档中它说您可以在初始主视图绘制在屏幕上后随时更改自定义键盘的高度。它说要做到这一点,你应该使用 .addConstaint() 方法。

这是一个链接: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/Keyboard.html

我正在使用 Swift。键盘的初始高度为 215 像素。我有一个向上滑动的手势,将高度增加到 350 像素。哪个按预期工作。向下滑动可将高度更改为 300 像素。

一切正常,但问题是它只能工作一次。我向上滑动,高度增加,向下滑动,高度减小,但如果我再次向上滑动,则没有任何反应。如果我再次向下滑动,则没有任何反应。

因此,如果有人可以查看我的两个函数并告诉我我做错了什么,我将非常感激。

代码如下:

// IBActions
@IBAction func action1(sender: AnyObject) {

    if topboxvisible == false {
        topboxvisible = true
    UIView.animateWithDuration(0.08, delay: 0, options: .CurveEaseIn, animations: {
        self.topbox.frame.offset(dx: 0, dy: 40)

        }, completion: nil)
    }
    let expandedHeight:CGFloat = 300
    let heightConstraint = NSLayoutConstraint(item:self.view,
        attribute: .Height,
        relatedBy: .Equal,
        toItem: nil,
        attribute: .NotAnAttribute,
        multiplier: 0.0,
        constant: expandedHeight)
    self.view.removeConstraint(heightConstraint)
    self.view.addConstraint(heightConstraint)
}

@IBAction func action2(sender: AnyObject) {
    if topboxvisible == true {
        topboxvisible = false
    UIView.animateWithDuration(0.08, delay: 0, options: .CurveEaseOut, animations: {
        self.topbox.frame.offset(dx: 0, dy: -40)
        }, completion: nil)
    }
    let expandedHeight:CGFloat = 350
    let heightConstraint = NSLayoutConstraint(item:self.view,
        attribute: .Height,
        relatedBy: .Equal,
        toItem: nil,
        attribute: .NotAnAttribute,
        multiplier: 0.0,
        constant: expandedHeight)
    self.view.removeConstraint(heightConstraint)
    self.view.addConstraint(heightConstraint)

}

【问题讨论】:

    标签: ios xcode swift autolayout ios8


    【解决方案1】:

    您的removeConstraint 调用没有执行任何操作,因为您刚刚创建的约束(在前一行代码中)不在视图中。因此,据我所知,您在这里所做的是每次都添加更多约束。我想这会导致多个冲突的约束——你在运行代码时是否看到控制台日志中弹出任何 NSConstraint 警告?

    试试这个:提前创建两个高度约束,并将它们存储在实例变量中。在action1中,移除350-high约束,并添加300。在action2中,移除300,并添加350。

    【讨论】:

    • 当我运行键盘时控制台是空白的,即使我上下滑动来创建约束也是如此。此外,当我将 NSLayoutConstraint 置于 IBAction 之外时,它说,KeyboardViewController 没有名为“view”的成员。对不起,如果这是一个nooby错误!
    • 扩展程序的日志可能不会在控制台显示,需要在Window -> Devices 中查看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2018-06-22
    • 2015-09-18
    • 2013-12-31
    • 1970-01-01
    • 2013-09-28
    • 2013-03-30
    相关资源
    最近更新 更多