简体   繁体   English

以编程方式更改情节提要视图的高度

[英]Programmatically changing the height of a Storyboard view

Background: 背景:

I have a normal UIView in Storyboard (called statusView ) which has a height of 30 , and four constraints pinned to the leading, trailing, top space to the superview, and bottom space to the view below it. 我在Storyboard中有一个普通的UIView (称为statusView ),其高度为30 ,并且四个约束固定到超视图的前导,尾随,顶部空间,以及其下面的视图的底部空间。

Problem: 问题:

My goal is to alter the height of statusView , including animating the frame changes when the user performs an action. 我的目标是更改statusView的高度,包括在用户执行操作时为帧更改设置动画。 As such, statusView could be as short as 0 or as tall as 100 . 这样, statusView可以短至0或高至100

My expectation is that, given statusView is constrained to the superview and its nearest neighbor below, it should automatically "push" the views below when I alter its height. 我的期望是,鉴于statusView视图及其下方的最近邻居,当我更改其高度时,它应自动“推”下面的视图。

Just to test, in viewDidAppear , I call the following: 为了测试,在viewDidAppear ,我调用以下代码:

self.statusView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 100.0)
self.statusView.setNeedsDisplay()

Issue : However, the height of 30 remains for statusView , despite me setting it to 0 . 问题 :但是,尽管我将其设置为0 ,但statusView的高度仍然为30。

Edit: posted Storyboard settings 编辑:发布的Storyboard设置

This is the setting for statusView : 这是statusView的设置: 在此处输入图片说明

If you are using autolayout and want to set an explicit height for a view in your hierarchy, you should use autolayout to do it. 如果您正在使用自动布局,并且想要为层次结构中的视图设置显式的高度,则应使用自动布局来实现。 I am assuming there is a height constraint set up in interface builder. 我假设在界面生成器中设置了高度限制。

Create an IBOutlet for the constraint and link it up in interface builder. 为约束创建一个IBOutlet并将其链接到接口构建器中。

@IBOutlet weak var statusViewHeightConstraint: NSLayoutConstraint!

Then, assuming this is just a size constraint with a constant for the height, just change it in your code: 然后,假设这只是一个大小约束,且高度为常数,则只需在代码中进行更改即可:

statusViewHeightConstraint.constant = 100

You can animate this change by wrapping a layout call in an animation block right after modifying your constraint(s). 您可以通过在修改约束后立即将布局调用包装在动画块中来动画化此更改。 Something like this: 像这样:

UIView.animateKeyframes(withDuration: 0.2, delay: 0.0, options: [.beginFromCurrentState, .calculationModeCubic], animations: {
  self.view.layoutIfNeeded()
}, completion: nil)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM