How To Update Uiview Frame Swift
This chapter is from the book
Views and Frames
When you initialize a view programmatically, y'all utilise its init(frame:) designated initializer. This method takes one argument, a CGRect , that volition go the view'southward frame, a belongings on UIView .
var frame: CGRect
A view's frame specifies the view'south size and its position relative to its superview. Because a view's size is always specified past its frame, a view is always a rectangle.
A CGRect contains the members origin and size. The origin is a structure of type CGPoint and contains two CGFloat properties: x and y. The size is a structure of type CGSize and has two CGFloat backdrop: width and acme (Figure 3.v).
When the awarding is launched, the view for the initial view controller is added to the root-level window. This view controller is represented by the ViewController class defined in ViewController.swift. Nosotros will talk over what a view controller is in Affiliate five, but for now, it is sufficient to know that a view controller has a view and that the view associated with the chief view controller for the application is added as a subview of the window.
Earlier you create the views for WorldTrotter, you lot are going to add together some practice views programmatically to explore views and their properties and see how the interfaces for applications are created.
Open up ViewController.swift and delete whatever methods that the template created. Your file should wait like this:
import UIKit form ViewController: UIViewController { }
(Curious about the import UIKit line? UIKit is a framework. A framework is a collection of related classes and resources. The UIKit framework defines many of the user interface elements that your users see, likewise equally other iOS-specific classes. You lot will be using a few dissimilar frameworks every bit yous go through this volume.)
Right after the view controller'south view is loaded into memory, its viewDidLoad() method is called. This method gives you an opportunity to customize the view hierarchy, so information technology is a great identify to add together your exercise views.
In ViewController.swift, override viewDidLoad() . Create a CGRect that will be the frame of a UIView . Side by side, create an instance of UIView and ready its backgroundColor holding to blue. Finally, add together the UIView equally a subview of the view controller's view to arrive part of the view bureaucracy. (Much of this will not wait familiar. That is fine. We will explain more afterward you enter the code.)
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) permit firstView = UIView(frame: firstFrame) firstView.backgroundColor = UIColor.blueColor() view.addSubview(firstView) } }
To create a CGRect , you use its initializer and pass in the values for origin.ten, origin.y, size.width, and size.height.
To ready the backgroundColor, you use the UIColor class method blueColor() . This is a convenience method that initializes an instance of UIColor that is configured to exist blue. In that location are a number of UIColor convenience methods for common colors, such as greenColor() , blackColor() , and clearColor() .
Build and run the application (Command-R). You will see a blueish rectangle that is the instance of UIView . Because the origin of the UIView 'southward frame is (160, 240), the rectangle's top left corner is 160 points to the correct and 240 points downward from the top left corner of its superview. The view stretches 100 points to the right and 150 points down from its origin, in accord with its frame'south size (Figure 3.6).
Note that these values are in points, not pixels. If the values were in pixels, and then they would non be consequent beyond displays of different resolutions (i.due east., Retina vs. not-Retina). A unmarried point is a relative unit of a measure out; it volition be a unlike number of pixels depending on how many pixels are in the display. Sizes, positions, lines, and curves are ever described in points to allow for differences in display resolution.
Figure 3.vii represents the view hierarchy that you have created.
Every instance of UIView has a superview holding. When you add together a view every bit a subview of another view, the inverse human relationship is automatically established. In this example, the UIView 's superview is the UIWindow .
Allow's experiment with the view hierarchy. First, in ViewController.swift, create another instance of UIView with a different frame and background color.
override func viewDidLoad() { super.viewDidLoad() let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150) permit firstView = UIView(frame: firstFrame) firstView.backgroundColor = UIColor.blueColor() view.addSubview(firstView) let secondFrame = CGRect(x: twenty, y: thirty, width: l, height: l) let secondView = UIView(frame: secondFrame) secondView.backgroundColor = UIColor.greenColor() view.addSubview(secondView) }
Build and run again. In improver to the blueish rectangle, you will see a green square almost the top lefthand corner of the window. Effigy three.8 shows the updated view bureaucracy.
Figure 3.viii Updated view bureaucracy with 2 subviews as siblings
At present you are going to adjust the view hierarchy so that one instance of UIView is a subview of the other UIView instead of the view controller'due south view. In ViewController.swift, add together secondView equally a subview of firstView.
... let secondView = UIView(frame: secondFrame) secondView.backgroundColor = UIColor.greenColor()view.addSubview(secondView)firstView.addSubview(secondView)
Your view hierarchy is now four levels deep, equally shown in Figure three.9.
Build and run the application. Discover that secondView's position on the screen has changed (Figure 3.10). A view'south frame is relative to its superview, so the pinnacle left corner of secondView is now inset (20, 30) points from the superlative left corner of firstView.
Effigy 3.10 WorldTrotter with new bureaucracy
(If the green instance of UIView looks smaller than it did previously, that is just an optical illusion. Its size has not changed.)
Now that you take seen the basics of views and the view hierarchy, you lot can start working on the interface for WorldTrotter. Instead of building up the interface programmatically, y'all will utilize Interface Builder to visually lay out the interface, as you did in Chapter i.
In ViewController.swift, starting time past removing your do code.
override func viewDidLoad() {super.viewDidLoad()let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150)let firstView = UIView(frame: firstFrame)firstView.backgroundColor = UIColor.blueColor()view.addSubview(firstView)let secondFrame = CGRect(x: 20, y: xxx, width: fifty, height: fifty)allow secondView = UIView(frame: secondFrame)secondView.backgroundColor = UIColor.greenColor()firstView.addSubview(secondView)}
Now allow's add some views to the interface and set their frames.
Open Main.storyboard. Observe that the interface on the screen is currently a square. While you lot explore views and their frames, it will be nice to accept the size of the interface in Xcode match the screen size of the device that you will exist using.
Select the View Controller either in the certificate outline or by clicking the yellow circumvolve above the interface. Open the attributes inspector, which is the 4th tab in the utilities expanse. You can quickly open up this pane using the keyboard shortcut Command-Choice-four.
At the top of the pane, find the department labeled Simulated Metrics and change the Size to be iPhone 4.vii-inch. This will resize the square interface to friction match the dimensions of the 4.7-inch devices.
From the object library, drag five instances of UILabel onto the sail. Space them out vertically on the peak half of the interface and centre them horizontally. Set their text to match Effigy 3.11.
Select the elevation label then y'all can see its frame in Interface Builder. Open its size inspector – the 5th tab in the utilities surface area. (Every bit you might have noticed by this point, the keyboard shortcuts for the utilities tabs are Control-Option plus the tab number. Since the size inspector is the 5th tab, its keyboard shortcut is Command-Option-5.)
Under the View section, discover Frame Rectangle. (If you lot do not see information technology, you might need to select it from the Show pop-upward bill of fare.) These values are the view's frame, and they dictate the position of the view on screen (Figure 3.12).
Figure 3.12 View frame values
Build and run the awarding on the iPhone 6s simulator. This corresponds to the 4.7-inch simulated metrics that you specified in the storyboard. The interface on the simulator will look identical to the interface that you laid out in Interface Architect.
Customizing the labels
Let's brand the interface look a little bit meliorate by customizing the view backdrop.
In Main.storyboard, select the background view. Open the attributes inspector and give the app a new background color: Find and click the Background dropdown and click Other. Select the 2nd tab (the Colour Sliders tab) and enter a Hex Color # of F5F4F1 (Figure three.xiii). This will give the background a warm, gray colour.
Effigy 3.thirteen Changing the background color
Y'all tin customize attributes mutual to selected views simultaneously. You volition use this to requite many of the labels a larger font size equally well as a burnt orange text color.
Select the superlative 2 and bottom two labels by Control-clicking them in the document outline and open the attributes inspector. Update the text color: Under the Label section, find Color and open the pop-up menu. Select the Color Sliders tab again and enter a Hex Color # of E15829.
Now permit'southward update the font. Select the 212 and 100 labels. Nether the Label department in the attributes inspector, find Font and click on the text icon next to the current font. From the popover that appears, make the Font Arrangement - System and the Size seventy (Effigy 3.14). Select the remaining 3 labels. Open their Font pop-up and make the Font System - System and the Size 36.
Figure three.fourteen Customizing the labels' font
At present that the font size is larger, the text no longer fits within the bounds of the characterization. Yous could resize the labels manually, but at that place is an easier way.
Select the meridian label on the sail. From Xcode'southward Editor menu, select Size to Fit Content (Command-=). This will resize the characterization to exactly fit its text contents. Echo the process for the other four labels. (You can select all four labels to resize them all at once.) Now motility the labels and then that they are over again nicely aligned vertically and centered horizontally (Figure 3.15).
Build and run the application on the iPhone 6s simulator. Now build and run the awarding on the iPhone 6s Plus simulator. Observe that the labels are no longer centered – instead, they appear shifted slightly to the left.
You have just seen two of the major problems with accented frames. Start, when the contents change (like when y'all changed the font size), the frames exercise not automatically update. 2d, the view does not look equally skilful on different sizes of screens.
In general, you should not utilise absolute frames for your views. Instead, you should apply Automobile Layout to flexibly compute the frames for you based on constraints that you specify for each view. For example, what you really want for WorldTrotter is for the labels to remain the aforementioned distance from the top of the screen and to remain horizontally centered within their superview. They should also update if the font or text of the labels modify. This is what you lot will accomplish in the side by side department.
Source: https://www.informit.com/articles/article.aspx?p=2474236&seqNum=4
Posted by: reynoldshomply.blogspot.com
0 Response to "How To Update Uiview Frame Swift"
Post a Comment