简体   繁体   中英

How do I create a new View (or subView) with the tap of a button in swift?

I am currently making a flashcard app, and I am trying to make a button that creates an entirely new View (or subView) for the user to edit. Should I use Container Views? Collection Views? I also want to have these set to only one View Controller, so I can save the "cards" in one "set". Please Help!!

Edit: How can I save these views in a "folder" so the user can look at them later. Is there an efficient way to do this so the app doesn't slow or stop.

Edit #2: Ok, so I'm kind of getting it... collection views. But how would I implement this into my because I am using tvOS. Any thoughts?

If you want to create a new UIView programmatically, it's actually quite simple. You could create a method like this:

func addNewView(to container: UIView) {

    let newView = UIView()
    container.addSubview(newView)
    newView.backgroundColor = UIColor.blue
    newView.frame = CGRect(x: 10, y: 50, width: 200, height: 250)

}

That would create a new view inside whichever container view you passed in with a blue background, 10pts from the left (x-axis), 50pts from the top (y-axis, think a normal cartesian coordinate system with the y-axis inverted), width of 200 and height of 250.

You could then call this method on the push of a button by handling a button tap with it's own method like this:

func buttonTapped(_ sender: UIButton) {

    addNewView(to: self.view)

}

Obviously all the values for the frame I gave you were just for an example so you could visualize it in your head, you can edit those however you want, or make calculations based on the size of your device's screen. You can get the device's screen size by saying self.view.bounds

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