ios - 如何使用 Swift 以编程方式增加 UIView 的高度

标签 ios swift xcode uiview constraints

在 IB 内部,我有一个带有 segmentedControl 和 2 个 containerView 的 viewController。在每个 containerView 中,我都有一个 tableView。我从每个 tableView 推送一个 detailView。我的自动布局在 IB 中。

一旦我选择了一个段,我就会看到相应的 tableView,我选择一个单元格,正确的 detailView 就会被推送到场景中。

问题是一旦 detailView 被推送到 segmentedControl 上仍然可见。我决定隐藏有效的 segmentedControl 但那里有很大的空白空间。我试图以编程方式增加 detailView View 的大小,但它没有扩展。据我了解,这是因为我在 Storyboard中进行了初始约束。

如何以编程方式让 detailView 的 View 展开?

代码:

DetailViewController: UIViewController{

override func viewDidLoad() {
        super.viewDidLoad()

 //this isn't increasing the view's size
 self.view.frame.size.height += 20.0

 //doesn't work. I get an error on the last argument
 self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height += 20.0)

 //doesn't work. I get an error on the last argument
 self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.size.height += 20.0)
 }

}

错误:

//Error for the last argument- height: *self.view.frame.height += 20.0*
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height += 20.0)

Left side of mutating operator isn't mutable: 'height' is a get-only property

//Error for the last argument- *self.view.frame.size.height += 20.0*:
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.size.height += 20.0)

Cannot invoke initializer for type 'CGRect' with an argument list of type '(x: Int, y: Int, width: CGFloat, height: ())'

最佳答案

您需要为详细 View 的高度约束创建一个导出,然后您可以像这样以编程方式调整高度 myHeightConstraint.constant += extraHeight where extraHeight是一个数字,表示您希望详细 View 的高度。之后您可能还需要调用 self.view.layoutIfNeeded()

要从约束创建导出,请控制从 Storyboard编辑器中的约束拖动(就像您对 UIView 的导出所做的那样)到您的代码中。

您是对的 - 因为您使用的是自动布局和约束,所以调整也需要使用约束进行。设置原始帧可能会导致意外行为。如果您有任何其他问题或困难,请告诉我。

关于ios - 如何使用 Swift 以编程方式增加 UIView 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43010173/

相关文章:

ios - 函数在收到响应后需要一段时间才能继续

ios - 向 Apple Watch 扩展程序发送通知

ios - generateCGImagesAsynchronouslyForTimes 花费的时间太长

ios - XCode iOS 改变现有项目的界面

objective-c - NSManagedObjectContext 困惑

ios - 动画自定义 UITableViewCell 时的计时问题

swift - 我如何在 swift 中以字典作为参数发出 http get 请求

ios - 如何在 ios 中的自定义表格单元格内创建按钮操作

swift - 如何快速绘制一个复杂的圆?

xcode - IOS MasterDetail Universal Project 如何添加登录?