简体   繁体   中英

Question about changing height of UIView when button is pressed in Swift

I am making a function that the height of a UIView increases and decreases when a button is pressed.

When the height of the UIView was reduced, the value created a layout in the storyboard, When the height of the UIView is increased, the value will be the height of the UITextView.

在此处输入图像描述

The picture above is before the UIView is stretched. Press the button at the bottom of the photo to stretch the UIView

在此处输入图像描述

The picture above is after the UIView is stretched. If you press the button at the bottom of the picture above, the UIView will shrink again.

The first thing I am curious about is the code to make the height of the UIView increase.

    @IBOutlet weak var bookInfoView: UIView!
    @IBOutlet weak var bookInfoVieweBtn: UIButton!
    @IBOutlet weak var bookInfoTextView: UITextView!

    @IBAction func bookInfoViewBtnTapped(_ sender: Any) {
        print("##bookInfoViewBtnTapped!")
        let f = bookInfoView.frame
        let textView = bookInfoTextView.frame
        bookInfoView.frame = CGRect(x: f.origin.x, y: f.origin.y, width: f.width, height:      textView.height)
    }

If you press the button using the code above, it does nothing. What should I do?

Follow below steps:-

  • Define height constraint in your storyboard.
  • create IBOutlet of height constraint
  • Then on button press, increase/decresse your height of textview like:-

     textViewHeightConstant.constant = someValue

1.Set some default value for the height of your the view your are trying to expand. Then if you are using StoryBoard make an IBOutlet to your ViewConroller, and remove the weak reference (that's because we are going to deactivate the height anchor and if it is weak and you deactivate it, the ARC will dealocate it. If your are going for it programatically just store the height anchor in a local variable. So it should like something like this:

@IBOutlet var yourViewHeightAnchor: NSLayoutConstraint!

2. Add a target to your button or if your using StoryBoard or Xib drag a IBAction to you ViewController. When the button is clicked, your only job is to deactive/active the height anchor. ( The activation will serve for collapse)

@IBAction func expandClicked(_ sender: Any) {
    yourViewHeightAnchor.isActive.toggle()
}

If you wish to use some animation for expanding/collapsing, your expandClicked function should look something like this:

@IBAction func expandClicked(_ sender: Any) {
    UIView.animate(withDuration: 0.6, animations: {
        self.yourViewHeightAnchor.isActive.toggle()
        self.view.layoutIfNeeded()
    })
}

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