Add Subview and Remove subview example in Swift

In this video, I am going to show you how to add a custom user interface as a subview and how to remove it from a super view on a button tap event.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Also, in this video, I am using the project I have created earlier. You can watch video tutorial and learn how I’ve created Custom User Interface in XIB file here: Creating Custom User Interface with XIB in Xcode 6 and Swift

Source code created during the video


import UIKit
class ViewController: UIViewController {

var mySubview:MyCustomView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func showSubviewButtonTapped(sender: AnyObject) {

if(mySubview != nil && !mySubview.view.hidden)
{
mySubview.view.removeFromSuperview()
}

mySubview = MyCustomView(frame: CGRect(x:10,y:300, width:275, height:147))

mySubview.titleLabel.text = “My custom label text”
mySubview.myButton.setTitle(“Hide”, forState: UIControlState.Normal)
mySubview.myButton.addTarget(self, action: “myHideButtonTapped:”, forControlEvents: UIControlEvents.TouchUpInside)

let catImage = UIImage(named: “cat1.jpeg”)
mySubview.myImage.image = catImage

self.view.addSubview(mySubview)

}

func myHideButtonTapped(sender:UIButton)
{
mySubview.view.removeFromSuperview()
}

}

I hope that this short Swift programming tutorial was helpful for you. There is some much more to learn about mobile apps development with Swift for iOS platform! Check the video courses below and may be one of them will be just what you need.