【问题标题】:Get UIView height and use it for its own constraints获取 UIView 高度并将其用于自己的约束
【发布时间】:2020-04-04 14:39:54
【问题描述】:

我的UIViewheight 怎样才能在实际呈现之前?

这是我尝试过的:

print(wishWishView.frame.size.height)

self.view.addSubview(self.wishWishView)

wishWishView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
wishWishView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

wishWishConstraint =  wishWishView.topAnchor.constraint(equalTo: self.view.bottomAnchor)
wishWishConstraint.isActive = true

UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
        self.transparentView.alpha = 0.7
        self.wishWishConstraint = self.wishWishView.topAnchor.constraint(equalTo: self.view.bottomAnchor, constant: - self.keyboardHeight)
        self.view.layoutIfNeeded()

    }, completion: nil)

问题是在实际呈现视图之前,wishWishView.frame.size.height0

我真正想要实现的是将视图隐藏在底部。我知道我可以只使用constant: 1000,但这是相当蛮力的,而且不是很干净。

编辑:

流程:

1.用户点击按钮

2. 视图从底部到右侧出现在 kayboard 上方

3.用户关闭视图

4.视图移到视图底部

Animation

我拥有所有 functionsvariablesfunc viewAppearskeyboardHeight、...),但我正在为 constraints 苦苦挣扎。

【问题讨论】:

  • 你想用第一个约束做什么?您将 wishWishView 的高度设置为等于自身。
  • 只是设置height
  • 你想让wishWishViewself.view 一样高吗?您需要设置它相对于另一个视图的高度或将其设置为常数。将其等同于自身没有任何作用。
  • 哦刚刚也意识到了.. 删除它,谢谢。您知道如何解决主要问题吗?
  • @Chris 那会很有帮助。我为我们创建了一个聊天室here

标签: ios swift uiview constraints


【解决方案1】:

为什么不删除最后一个约束,而是将视图的顶部锚点固定到其父视图的底部锚点。现在您已经按照自己的意愿隐藏了视图。

然后,当您想取消隐藏视图时,只需更改该约束的常量(您可以在此处使用视图的高度),然后在 UIView 动画块中调用 layoutIfNeeded()。

【讨论】:

  • 我更新了我的问题并尝试使用您的解决方案,但无法使其正常工作
  • 在添加约束之前,您是否正在做 wishView.translatesAutoresizingMaskIntoConstraints = false?
  • 此外,您存储了约束,但实际上并没有更改该约束;你正在重新分配一个新的。你需要像这样修改它,例如 self.myConstraint.constant = 100。然后把你的动画块放在后面。
  • 看看我的回答
【解决方案2】:

所以我解决了我的问题,动画现在按预期工作。然而,实际问题仍未解决。

let height = CGFloat(130)

@objc func addWishButtonTapped(){    

    let screenSize = UIScreen.main.bounds.size
    self.wishWishView.frame = CGRect(x: 0, y: screenSize.height, width: screenSize.width, height: height)
    self.view.addSubview(self.wishWishView)

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
    self.transparentView.alpha = 0.7
    self.wishWishView.frame = CGRect(x: 0, y: screenSize.height - self.height - self.keyboardHeight, width: screenSize.width, height: self.height)

}, completion: nil)

如您所见,我使用的是硬编码的height...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2020-07-22
    相关资源
    最近更新 更多