I am a newbie at Swift, and I want to learn how to display six labels side by side programmatically. I have the code to display a single object, but I do not know how to expand it for more objects. The code I have is below
class ViewController: UIViewController {
// MARK: - Properties
private var label1: CGPoint = CGPoint(x: 1000, y: 100)
private var label2: CGPoint = CGPoint(x: 150, y: 150)
private var label3: CGPoint = CGPoint(x: 200, y: 200)
private var label4: CGPoint = CGPoint(x: 250, y: 250)
private var label5: CGPoint = CGPoint(x: 300, y: 300)
private var label6: CGPoint = CGPoint(x: 350, y: 350)
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Add to View Hierarchy
view.addSubview(pannableView) //This creates the object, how to send more than one object
pannableView.center = view.center
// Initialize Swipe Gesture Recognizer
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
// Add Swipe Gesture Recognizer
pannableView.addGestureRecognizer(panGestureRecognizer)
}
// MARK: -
private let pannableView: UIView = {
// Initialize View
let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 80.0, height: 80.0))) //How big the object is
// Configure View
view.backgroundColor = .blue
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: - Actions
@objc private func didPan(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
label1 = pannableView.center
case .changed:
let translation = sender.translation(in: view)
pannableView.center = CGPoint(x: label1.x + translation.x,
y: label1.y + translation.y)
default:
break
}
}
}
I assume I need to define all the labels I have done, but when it goes to pannableView, it will only display "label1". I have seen some posts that involve making a table, but I don't think this works because I need to drag the label across the entire screen. Any advice is very much appreciated.
I think you should use UIStackView or UICollectionView of UIKit. If you want to create your stack view from scratch for studying, you should create YourOwnStackView class inherit from UIView and constraint arranged subviews in there.