简体   繁体   中英

Get UIView height and use it for its own constraints

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 .

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.

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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