create 2 labels with one expan in swift

To create two labels with one expan in Swift, you can follow the steps below:

  1. Open Xcode and create a new project.
  2. Drag and drop a UIView onto the view controller in the storyboard.
  3. Add two UILabels inside the UIView and connect them to the view controller as outlets.
  4. Set the text for both labels.
main.swift
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!

label1.text = "Label 1"
label2.text = "Label 2"
121 chars
6 lines
  1. Add a UILabel to act as the expander, connect it to the view controller as an outlet.
main.swift
@IBOutlet weak var expander: UILabel!
38 chars
2 lines
  1. Create a TapGestureRecognizer for the expander.
main.swift
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
expander.addGestureRecognizer(tapGesture)
expander.isUserInteractionEnabled = true
171 chars
4 lines
  1. Add the following method to handle the tap event:
main.swift
var isExpanded = false

@objc func handleTap(_ sender: UITapGestureRecognizer) {
    if isExpanded {
        label1.heightAnchor.constraint(equalTo: expander.heightAnchor).isActive = false
        label2.heightAnchor.constraint(equalTo: expander.heightAnchor).isActive = false
        isExpanded = false
    } else {
        label1.heightAnchor.constraint(equalTo: expander.heightAnchor, multiplier: 2).isActive = true
        label2.heightAnchor.constraint(equalTo: expander.heightAnchor, multiplier: 2).isActive = true
        isExpanded = true
    }
}
555 chars
14 lines

This method toggles the isExpanded boolean value and sets the height constraint of the two UILabels to either the height of the expander or twice the height of the expander, depending on the state of isExpanded.

Finally, add constraints to ensure that the UILabels and expander are positioned and sized correctly in the UIView, and run the app to test the functionality.

gistlibby LogSnag