IOS TOPICS

IOS Introduction
Swift UI Label
Swift UI Button
Swift UI Text Field
Swift UI Slider
Swift UI Switch
Swift UI Stepper
Swift UI Date Picker
Swift UI Segmented Control
Views
Table View
Collection Views
SCROLL VIEW
iOS Content View
iOS View Controllers
iOS Bar interface
iOS Navigation interface
iOS Architect Pattern
iOS Libraries
iOS Web request and parsing
iOS user defaults
iOS Coredata and database

Clipping subviews


Clipping subviews

Parent views don’t clip subviews to retain them within boundaries as we can see below

Code:

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) //use colorliteral to get a variety of color options let newView = UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 50)) let newView2 = UIView(frame: CGRect(x: 6, y: 6, width: 400, height: 100)) newView.backgroundColor = UIColor.white newView2.backgroundColor = UIColor.black view.addSubview(newView) newView.addSubview(newView2) } }

Output:

ios output

To retain the black rectangle within the white one, we need to clip it to the borders of the latter as shown below

Code:

view.backgroundColor = colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) //use color literal to get a variety of color options let newView = UIView(frame: CGRect(x: 10, y: 100, width: 300, height: 50)) newView.clipsToBounds = true let newView2 = UIView(frame: CGRect(x: 6, y: 6, width: 400, height: 100)) newView.backgroundColor = UIColor.white newView2.backgroundColor = UIColor.black view.addSubview(newView) newView.addSubview(newView2)

Output:

So the black view cannot extend extend beyond the white rectangle

ios output

Tip:

The co-ordinate system here works with 0,0 starting at the top left corner and the x increases on the right and y increases as we go tot he bottom of the screen. Each new subview’s origin starts at the top left corner of its parent view.