Get UIView height and use it for its own constraints

♀尐吖头ヾ 提交于 2020-04-16 05:47:12

问题


How can I can the height of my UIView before it is actually presented?

This is what I tried:

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)

The problem is that wishWishView.frame.size.height is 0 until the view is actually presented.

What I actually want to achieve is to hide the view at the bottom. I know I could just use constant: 1000 but that's quite brute force and not very clean.

Edit:

Process:

1. user taps on button

2. view appears from the bottom to right above the kayboard

3. user dismisses the view

4. view moves to the bottom out of the view

Animation

I have all the functions and variables (func viewAppears, keyboardHeight,...), but I am struggling with the constraints.


回答1:


Why don't you remove that last constraint, and instead, peg your view's top anchor to its superview's bottom anchor. Now you've hidden the view like you wanted.

Then when you want to unhide the view, simply change the constant of that constraint (you can use the height of your view here), and call layoutIfNeeded() in a UIView animation block.




回答2:


So I solved my problem and the animation is now working as expected. However the actual problem is still unsolved.

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)

As you can see I am using the hard-coded height...



来源:https://stackoverflow.com/questions/61029738/get-uiview-height-and-use-it-for-its-own-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!