<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by NPSoftware on Medium]]></title>
        <description><![CDATA[Stories by NPSoftware on Medium]]></description>
        <link>https://medium.com/@thanhtra.sqcb?source=rss-2337ce422add------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DoAHWTovSrDSy8iXL418nw.png</url>
            <title>Stories by NPSoftware on Medium</title>
            <link>https://medium.com/@thanhtra.sqcb?source=rss-2337ce422add------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:56:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thanhtra.sqcb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[12 - Navigation Bar Customization, Dark Mode, and Dynamic Type (UIKit)]]></title>
            <link>https://medium.com/@thanhtra.sqcb/12-navigation-bar-customization-dark-mode-and-dynamic-type-uikit-b41007cb8fb8?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/b41007cb8fb8</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 12:41:50 GMT</pubDate>
            <atom:updated>2023-03-02T12:41:50.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B98LxHCulx6rzEsIR-OLIA.png" /></figure><p>The detail view that we built is already great, but we will make it even more attractive in this chapter. Figure 15–1 shows the improved design with the following changes:</p><ol><li>Customizing the navigation bar to make it transparent, so that the restaurant image shifts to the top of the screen.</li><li>Customizing the back button. Instead of using the default back button, we use our own back icon and remove the title of the back button.</li><li>Changing the color of the status bar. To cater for dark content, it is better for us to change the color of the status bar to white.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-TXWTc_mK-4ASZpChpfdA.png" /><figcaption><em>Figure 15–1. Customizing the navigation bar and status bar</em></figcaption></figure><p>On top of that, I want to show you how to customize the large title of the navigation bar on the home screen. There are three changes we are going to perform:</p><ol><li>Customizing the background of the navigation bar and make it transparent.</li><li>Change the font of the large title and make its color adaptable to different interface style (light/dark mode).</li><li>Hide the navigation bar when users swipe the table view.</li></ol><p>In the first two section of this chapter, we will focus on the customization of the navigation bar and status bar. Thereafter, I will discuss with you about Dynamic Type, a technology built into iOS that lets users choose their preferred text size. While working on the project, I will also show you how to use Swift extensions to simplify our code.</p><p>Let’s start with the navigation bar customization.</p><h3>Customizing the Navigation Bar</h3><p>We will start with the customization of the home screen. What we are going to do is to make its background transparent and change the color of the title.</p><p>Starting from iOS 13, Apple introduced a new class called UINavigationBarAppearance for customizing the navigation bar. You can apply the customization to the navigation bar of a particular view or the whole application. I will demonstrate both cases in this chapter.</p><p>Let’s open the RestaurantTableViewController.swift file. Insert the following lines of code in the viewDidLoad() method:</p><pre>if let appearance = navigationController?.navigationBar.standardAppearance {<br><br>    appearance.configureWithTransparentBackground()<br><br>    if let customFont = UIFont(name: &quot;Nunito-Bold&quot;, size: 45.0) {<br><br>        appearance.titleTextAttributes = [.foregroundColor: UIColor(red: 218/255, green: 96/255, blue: 51/255, alpha: 1.0)]<br>        appearance.largeTitleTextAttributes = [.foregroundColor: UIColor(red: 218/255, green: 96/255, blue: 51/255, alpha: 1.0), .font: customFont]<br>    }<br><br>    navigationController?.navigationBar.standardAppearance = appearance<br>    navigationController?.navigationBar.compactAppearance = appearance<br>    navigationController?.navigationBar.scrollEdgeAppearance = appearance<br>}</pre><p>To customize the navigation bar, you first need to retrieve the current UINavigationBarAppearance object. The standardAppearance property contains the current appearance settings for the standard size navigation bar. The next step is to modify the properties of the appearance object and apply our customizations. The configureWithTransparentBackground() function configures the navigation bar with a transparent background and no shadow.</p><p>To change the bar title’s color and font, you modify the titleTextAttributes and largeTitleTextAttributes properties. Both properties accept a set of attributes in key/value format. The titleTextAttributes is designed for the standard-size title, while the largeTitleTextAttributes property is used when displaying large-size title. In the code above, we modify the font color and apply our custom font.</p><p>Even though we have completed the modification of the appearance object, the customization will not be applied to the navigation bar immediately. You have to assign the object to the standardAppearance, compactAppearance, and scrollEdgeAppearance properties. Each of these properties is responsible for the appearance of the navigation bar at different state. The standardAppearance property stores the appearance settings of the standard size navigation bar, while the setting of compactAppearance controls the appearance of the compact size navigation bar. scrollEdgeAppearance is the appearance settings to use when the edge of any scrollable content reaches the matching edge of the navigation bar.</p><p>Now run the app to have a quick test. You should see the result displayed in figure 15–2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzUAlOq1uhBYD9SKpArl1Q.png" /><figcaption><em>Figure 15–2. The custom navigation bar in light and dark modes</em></figcaption></figure><p>Now let’s move on to the detailed view. What we want to do is to shift the table view upwards towards the top edge of the screen. Insert the following code in the viewDidLoad() method of RestaurantDetailViewController:</p><pre>tableView.contentInsetAdjustmentBehavior = .never</pre><p>The value of the contentInsetAdjustmentBehavior property controls the behavior for determining the adjusted content offsets of the table view. By default, it is set to .always. In this case, iOS automatically adjusts the content offset of the table view such that the content area will not be blocked by the navigation bar (see figure 15-3 (left)). Now we set contentInsetAdjustmentBehavior to .never, telling iOS not to adjust the content area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8Kkz7peSGEIud3-U5cRsA.png" /><figcaption><em>Figure 15–3. contentInsetAdjustmentBehavior sets to .alway (left), contentInsetAdjustmentBehavior sets to .never (right)</em></figcaption></figure><p>As mentioned at the beginning of this chapter, we also want to customize the back button icon of the navigation controller. Instead of using the default image, we want to display an arrow image (i.e. arrow.backward) from SF Symbols.</p><p>The UINavigationBarAppearance object also provides you with a function called setBackIndicatorImage for changing the back button image like this:</p><pre>var backButtonImage = UIImage(systemName: &quot;arrow.backward&quot;, withConfiguration: UIImage.SymbolConfiguration(pointSize: 20.0, weight: .bold))<br><br>backButtonImage = backButtonImage?.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0))<br>appearance.setBackIndicatorImage(backButtonImage, transitionMaskImage: backButtonImage)</pre><p>In the sample code above, we load a system image and enlarge it by passing our symbol configuration. To change the back button image, you can call setBackIndicatorImage of the UINavigationBarAppearance object and pass it our own image. Optionally, we adjust the back button image&#39;s position by using withAlignmentRectInsets.</p><p>This is a global change that applies to all screens with a back button, not just a single view. Therefore, we will not modify the appearance object in Restaurant TableViewController to apply the change.</p><p>The question is: <em>where should we put the code above?</em></p><p>The AppDelegate class is sort of the entry point of the application. The class is generated by Xcode when your project is created from a project template. Typically we put this customization code in the application(_:didFinishLaunchingWithOptions:) method of the AppDelegate class. This method will be called when the application loads up and is suitable for adding customization code that affects the entire application.</p><p>Now, update the application(_:didFinishLaunchingWithOptions:) method of AppDelegate like this:</p><pre>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br><br>    let navBarAppearance = UINavigationBarAppearance()<br><br>    var backButtonImage = UIImage(systemName: &quot;arrow.backward&quot;, withConfiguration: UIImage.SymbolConfiguration(pointSize: 20.0, weight: .bold))<br><br>    backButtonImage = backButtonImage?.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0))<br>    navBarAppearance.setBackIndicatorImage(backButtonImage, transitionMaskImage: backButtonImage)<br><br>    UINavigationBar.appearance().tintColor = .white<br>    UINavigationBar.appearance().standardAppearance = navBarAppearance<br>    UINavigationBar.appearance().compactAppearance = navBarAppearance<br>    UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance<br><br>    return true<br><br>}</pre><p>In the code above, we first create the UINavigationBarAppearance object and change the back button image. The modified appearance object is then assigned to the standardAppearance, compactAppearance, and scrollEdgeAppearance properties.</p><p>That’s it! You can now run your app and have a look. Since we also change the tintColorproperty of the navigation bar, the back button icon should be changed to a white arrow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyAb5CuRdHnVR2lOjcmb7Q.png" /><figcaption><em>Figure 15–4. Changing the back button image</em></figcaption></figure><p>As you can see, the app still shows the back button title. If you want to remove the title, open RestaurantTableViewController.swift and add the following line of code in the viewDidLoad()method:</p><pre>navigationItem.backButtonTitle = &quot;&quot;</pre><p>Test the app again, the navigation bar should no longer display the back button title.</p><h3>Hiding a Navigation Bar on Swipe</h3><p>Since iOS 8, Apple has introduced a nifty feature which allows you to hide a navigation bar on swipe or tap. This feature shouldn’t be new to you. When scrolling down a web page in mobile Safari, the address bar is condensed and the toolbar goes away. If you want to build this feature in your app, you will need a click or a line of code to enable this feature.</p><p>In Main storyboard, select the navigation controller in the navigation controller scene. In the Attribute inspector, there is an option named On Swipe under the navigation controller section. When enabled, your app will hide the navigation bar, as well as, toolbar (if any) when a user scrolls down the content view. The bars appear again when the user swipes back up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2beWXasaQV1GP4Ubx6ZSXQ.png" /><figcaption><em>Figure 15–5. On Swipe option for hiding the bars</em></figcaption></figure><p>This change applies to all navigation bars of the entire app. That means, both the restaurant table view controller and the detail view controller are automatically enabled with the feature. What if we just want to hide the navigation bar for the restaurant table view controller? It would be better for us to do this in code.</p><pre>Note: If you&#39;ve enabled the On Swipe option in Interface Builder, please disable it before moving on because we will set the option programmatically.</pre><p>To hide the bars on swipe, you set the hidesBarsOnSwipe property to true using the code below:</p><pre>navigationController?.hidesBarsOnSwipe = true</pre><p>Let’s add the line above in the viewDidLoad method of RestaurantTableViewController. After that, run the app to have a quick test. Swipe up the table view and the navigator bar will be hidden. It works pretty well.</p><p>However, if you select a restaurant to navigate to the detailed view, this swipe-to-hide feature is enabled too. Okay, we want to disable the swipe-to-hide feature in the detail view. Let’s add the following code in the viewDidLoad method of RestaurantDetailViewController to disable it:</p><pre>navigationController?.hidesBarsOnSwipe = false</pre><p>Run the app again to test it. Does it fix the issue?</p><p>At first, it looks like we have fixed the navigation bar issue. But if you test more thoroughly, you will find other issues as illustrated in figure 15–6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DybN8mQeDK2OeSqNP6hPg.png" /><figcaption><em>Figure 15–6. Possible issues when setting the hidesBarsOnSwipe property in the viewDidLoad method</em></figcaption></figure><p>We briefly discussed the view controller life cycle. iOS calls the viewDidLoad method when the view controller’s content view is first created and loaded from a storyboard. This is why we use to set up our outlet variables or perform other initializations in viewDidLoad.</p><p>However, keep in mind that the viewDidLoad method is called only once when the view is first loaded. After that, it won&#39;t be called again. In other words, if you navigate to the detail view, the hidesBarsOnSwipe property is set to false. And the value will keep intact even when you navigate back to the table view controller. This is the reason why the navigation bar won&#39;t hide (Problem #1).</p><p>For Problem #2, the hidden navigation bar is carried over to the detail view. Even if we manage to set the hidesBarsOnSwipe property back to false in the viewDidLoad method, it won&#39;t display the navigation bar. We have to explicitly tell the app to re-display the navigation bar.</p><p>Fortunately, the UIViewController class provides several methods that respond to different view states. Unlike the viewDidLoad method, these methods are called every time when a view is displayed or removed. When a view is displayed, both viewWillAppear and viewDidAppearmethods are invoked. The viewWillAppear method is called when the view is about to display, whereas the viewDidAppear method is triggered as soon as the view is presented on screen.</p><p>Apparently, the viewWillAppear method fits our need. Insert the following code in the RestaurantTableViewController class:</p><pre>override func viewWillAppear(_ animated: Bool) {<br>    super.viewWillAppear(animated)<br>    navigationController?.hidesBarsOnSwipe = true<br>}</pre><p>For the RestaurantDetailViewController class, add the following code snippet:</p><pre>override func viewWillAppear(_ animated: Bool) {<br>    super.viewWillAppear(animated)<br>    navigationController?.hidesBarsOnSwipe = false<br>    navigationController?.setNavigationBarHidden(false, animated: true)<br>}</pre><p>As the viewWillAppear method is called every time when a view is displayed, we can toggle the hidesBarsOnSwipe property perfectly. The extra line of code in the RestaurantDetailViewController class explicitly tells the app to unhide the navigation bar. This resolves problem #2. One thing to take note is that you must call the super method at some point of the implementation. After the changes, run the app and have fun!</p><h3>Exercise #1</h3><p>Before we continue to work on the new features of the app, let’s fix a bug that you may notice for some time. In the main view, we use the large title for the navigation bar. Did you notice that the navigation bar becomes a standard size bar when you navigate from the detailed view back to the main view?</p><p>Your exercise is to fix this bug such that the navigation bar of the main view (i.e. RestaurantTableViewController) always shows large title.</p><h3>Swift Extensions</h3><p>Before I go on to discuss with you about other UI customizations, I want to take a detour here and talk about a feature in Swift known as <em>Extensions</em>. We have discussed extensions before but I want to go a little deeper and show you how to utilize this powerful Swift feature.</p><p>Extensions in Swift is a great feature that lets you add new functionality to an existing class or other types including Struct and Enum . What does it mean to you? How can you use this feature to write better code? Let me show an example.</p><p>If you look into the RestaurantTableViewController class, you will find multiple lines of code related to the initialization of UIColor like this:</p><pre>UIColor(red: 218/255, green: 96/255, blue: 51/255, alpha: 1.0)</pre><p>Here we instantiate a UIColor object with custom RGB values. Because UIColor only accepts the RGB value in the scale of 0 to 1, we have to divide each of the RGB components by 255 during initialization.</p><p>It is a bit troublesome. Can we simplify the code above to this?</p><pre>UIColor(red: 218, green: 96, blue: 51)</pre><p>Here we can apply extensions to extend the functionality of UIColor. Even though UIColor is a built-in class provided by the iOS SDK, we can use Swift extensions to add more features to it.</p><p>To better organize our projects, let’s first create a group for storing the extension file. In project navigator, right click the FoodPin folder and choose <em>New Group</em>. Name the group <em>Extensions</em>.</p><p>Next, right click Extensions and select <em>New File…</em>. Choose the <em>Swift File</em> template and name the file UIColor+Ext.swift. Once the file is created, update the code like this:</p><pre>import UIKit<br><br>extension UIColor {<br>    convenience init(red: Int, green: Int, blue: Int) {<br>        let redValue = CGFloat(red) / 255.0<br>        let greenValue = CGFloat(green) / 255.0<br>        let blueValue = CGFloat(blue) / 255.0<br>        self.init(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)<br>    }<br>}</pre><p>To declare an extension for an existing class, you start with the keyword extension followed by the class you want to extend. Here it is the UIColor class.</p><p>We implement an additional convenience initializer that accepts three parameters: <em>red</em>, <em>green</em>and <em>blue</em>. In the body of the initializer, we perform the conversion by dividing the given RGB value by 255. Finally, we call the original init method with the converted RGB components.</p><p>That’s how you use Swift extensions to add another initializer to a built-in class. Now the new initializer is ready for use. For example, you can change the following line of code in RestaurantTableViewController from:</p><pre>appearance.titleTextAttributes = [.foregroundColor: UIColor(red: 218/255, green: 96/255, blue: 51/255, alpha: 1.0)]</pre><p>To:</p><pre>appearance.titleTextAttributes = [.foregroundColor: UIColor(red: 218, green: 96, blue: 51, alpha: 1.0)]</pre><p>Can you still use the original initializer? Absolutely. The new initializer just simplifies the redundant conversion and lets you type less code.</p><h3>Adapting Colors for Dark Mode</h3><p>With the introduction of Dark Mode, your app should cater for both light and dark appearance. Up till now, the FoodPin app works pretty well in Dark mode. One main reason is that we mostly use the built-in adaptive colors provided by Apple.</p><p>Along the debut of Dark Mode in iOS 13, Apple introduced two types of built-in color: <em>system colors</em> and <em>semantic colors</em>. All these colors are designed to adapt to different system environment. Whether you choose the system color or the semantic color, the color looks good on both light and dark appearance. As mentioned before, the same system color (say, System Red Color) has different color values for different interface styles.</p><p>Like System colors, semantic colors are also designed to be adaptive and return different color values for different interface styles. The color name describes the intention of the color. For example, <em>Label Color</em> is created for label and <em>System Background Color</em> is used for painting the view’s background</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhM5eeziEwvWSoPof0PAhw.png" /><figcaption><em>Figure 15–7. Adaptive and semantic colors</em></figcaption></figure><p>According to Apple, developers are encouraged to use system and semantic colors because it makes you a lot easier to support dark mode. You should avoid creating a UIColor object with hardcoded color values. That said, what if we want to use our own color instead of the built-in ones like the one we used for the navigation bar title?</p><p>In the asset catalog, you can create your custom color that has different color values for light and dark appearance. Right any blank area in the asset catalog to bring up the context menu. Select <em>New Color Set</em> to add a new color set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSgvM_vzCWu2qBwH5RBtWw.png" /><figcaption><em>Figure 15–8. Adding a new color set in asset catalog</em></figcaption></figure><p>Name the color set NavigationBarTitle and then you will need to fill in two different color for <em>Any Appearance</em> and <em>Dark Appearance</em>. First, select <em>Any Appearance</em> and go to the Attributes inspector. Change the input method to <em>8-bit Hexidecimal</em> and set the Hex value to #DA6033.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Er0DCIuLxWMCelif7nWIjg.png" /><figcaption><em>Figure 15–9. Setting the color for Any Appearance</em></figcaption></figure><p>Repeat the same procedures but set the color for Dark Appearance. We use a different color value for this interface style, so set the <em>Hex</em> value to #D35400. This is how you define a custom semantic color.</p><p>To use this custom color, you can create the UIColor instance with the color name like this:</p><pre>let color = UIColor(named: &quot;NavigationBarTitle&quot;)!</pre><p>Now you can replace the following lines of code in the viewDidLoad() method of RestaurantTableViewController:</p><pre>appearance.titleTextAttributes = [.foregroundColor: UIColor(red: 218, green: 96, blue: 51, alpha: 1.0)]<br>appearance.largeTitleTextAttributes = [.foregroundColor: UIColor(red: 218, green: 96, blue: 51, alpha: 1.0), .font: customFont]</pre><p>With:</p><pre>appearance.titleTextAttributes = [.foregroundColor: UIColor(named: &quot;NavigationBarTitle&quot;)!]<br>appearance.largeTitleTextAttributes = [.foregroundColor: UIColor(named: &quot;NavigationBarTitle&quot;)!, .font: customFont]</pre><p>Run the app to have a quick test. The navigation bar title now has different colors in light and dark mode.</p><h3>Changing the Style of Status Bar</h3><p>Now let’s head back to the UI customization. The style of the status bar looks great on the home screen but doesn’t go well with the restaurant image in the detail view. Wouldn’t it be great if we can change the color of the status bar to white for the detail view?</p><p>The iOS SDK allows developers to use a UIStatusBarStyle constant to specify whether the status bar content should be dark or light. By default, the status bar displays dark content. In other words, items such as time, battery indicator and Wi-Fi signal are displayed in dark color.</p><p>You may want to change the style of status bar from dark to light to make the app look better. There are two ways to do this. You can change the status bar style for the entire application or just change the style of individual controllers.</p><p>Apparently, the status bar style varies from view controller to view controller for the FoodPin app. For the home screen, we want to keep the default style, while the status of the detail view should change to the <em>light</em> style.</p><p>Normally, to control the style of the status bar in any view controller, you can add the following code in your class to override the preferredStatusBarStyle property and return your preferred style:</p><pre>override var preferredStatusBarStyle: UIStatusBarStyle {<br>    return .lightContent<br>}</pre><p>You can insert the code above in the RestaurantDetailViewController class to have a try.</p><p>Unfortunately, the above code does not work in this case.</p><p>The reason is that the detail view controller is embedded in a navigation controller. iOS uses the default style specified in the navigation controller instead.</p><p>So how can we tell iOS to change the status bar style?</p><p>It is a bit tricky. You need to create a custom UINavigationController class and override its preferredStatusBarStyle property. In the project navigator, right click the Controller group and choose <em>New File...</em> Select the <em>Cocoa Touch Class</em> template and name the class NavigationController. Set the subclass to UINavigationController. Update the code like this:</p><pre>class NavigationController: UINavigationController {<br>        override var preferredStatusBarStyle: UIStatusBarStyle {<br>        return topViewController?.preferredStatusBarStyle ?? .default<br>    }<br>}</pre><p>We override the preferredStatusBarStyle property such that it returns the value of preferredStatusBarStyle of the top view controller. Here, the topViewController is the view controller at the top of the navigation stack. In the case of the detailed view, the RestaurantDetailViewController is the top view controller.</p><p>Lastly, switch over to the Main storyboard. We need to update the navigation controller to use our custom navigation controller. Select the <em>Navigation Controller</em> in the document view and then change the custom class in the Identity inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zj7HcO2jSqT1TcUQajA4Uw.png" /><figcaption><em>Figure 15–10. Changing the custom class to NavigationController</em></figcaption></figure><p>Now run the app again to see what you get. The status bar should be changed to white in the detailed view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEtV6hNnvT__sps4LKmzmQ.png" /><figcaption><em>Figure 15–11. The detailed view shows the status bar in white</em></figcaption></figure><p>This is how you manage the status bar style for individual controllers. Though this is good enough for our app, I want to take a few minutes to show you how to change the style of the status bar across the entire application.</p><p>To do that, you can select the <em>FoodPin</em> project in the project navigator. In the <em>General</em> tab, you can change the status bar style to <em>Light Content</em>. This will change the status bar style for the entire application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsyLQR9n0pM8442GWNM0DA.png" /><figcaption><em>Figure 15–12. Changing the status bar style</em></figcaption></figure><p>However, there is one thing you need to configure before this modification works.</p><p>By default, the Xcode project is enabled to use “View controller-based status bar appearance”. This means you can control the appearance of the status per view controller. If you want to change the style of the status bar globally, you need to opt out the <em>View controller-based status bar appearance</em> by modifying the Info.plist file.</p><p>Select the file to open it. Right click <em>Information Property List</em> and select <em>Add Row</em>. Insert a new key named View controller-based status bar appearance and set the value to NO. This instructs Xcode to use the status bar setting we set in the <em>General</em> tab earlier. Now the entire app will use the new status style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pifge47M18Rf4gizBIpAWQ.png" /><figcaption><em>Figure 15–13. Editing the Info.plist to add a new key</em></figcaption></figure><h3>Dynamic Type</h3><p>What is Dynamic Type? You may not have heard of Dynamic Type but you should have seen the setting screen (<em>Settings &gt; Accessibility &gt; Display &amp; Text Size &gt; Large Text</em> or <em>Settings &gt; Display &amp; Brightness &gt; Text Size</em>) shown in figure 15–14.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eWpdtPoLtROAh1re6uWvw.png" /><figcaption><em>Figure 15–14. Larger Text Setting</em></figcaption></figure><p>Dynamic Type is not new and has been introduced since iOS 7. With this feature, users are able to customize the text size of an app to fit their own needs. However, there is a catch — only apps that adopt Dynamic Type respond to the text change.</p><p>All of the stock apps have adopted Dynamic Type. For third party apps, it is up to developers’ decision. Though Apple doesn’t mandate developers to support Dynamic Type, it is always recommended so users can choose their own text size.</p><p>So how can you adopt Dynamic Type? As we have designed our views using auto layout, adopting Dynamic Type is just a piece of cake. Recalled that we configured all the labels to use text style, this is what you need to adopt Dynamic Type: <em>use a text style instead of a fixed font type.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNbnzI0dYm8CAT0rJ-HSKg.png" /><figcaption><em>Figure 15–15. The name label is configured with a text style</em></figcaption></figure><p>So, how can you test dynamic types using the built-in simulator? One way is to change the setting in the simulator by going to <em>Settings &gt; Accessibility &gt; Display &amp; Text Size &gt; Large Text</em>. Enable <em>Larger Accessibility Sizes</em> and drag the slider to your right to enlarge the font.</p><p>A more convenience approach is use the <em>Environment Overrides</em> option in Xcode. While running the app in simulators, click the <em>Environment Overrides</em> button and switch on the Text option. You can use the Dynamic Type slider to adjust the font size. In the simulator, the app should respond to the size change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQi8e4g7wF2oetjRbMCZQw.png" /><figcaption><em>Figure 15–16. Using Environment Overrides to test dynamic types</em></figcaption></figure><p>There is an issue with the current implementation. In the simulator, go to <em>Settings &gt; Accessibility &gt; Display &amp; Text Size &gt; Large Text</em>. Enable <em>Larger Accessibility Sizes</em> and increase the text size. Switch back to the simulator. You should find that the size of the labels remains unchanged. However, if you rerun the app again, the font size will change accordingly.</p><p>How can we fix that?</p><p>There is an option in text labels called <em>Automatically Adjusts Font</em>, which is disabled by default. When this option is enabled, it will listen to the change of the text size in the system settings and update to the new size automatically.</p><p>Go to Main and select the name label of the restaurant table view controller. In the Attributes inspector, enable the <em>Automatically Adjusts Font</em> option. Repeat the same procedures for other labels. By turning on the option, the label will be automatically resized whenever the user changes the preferred font size in Settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfnoEllzY854qcHQPYCpWw.png" /><figcaption><em>Figure 15–17. Enabling the Automatically Adjusts Font option</em></figcaption></figure><p>Alternatively, you can also apply the change by setting the adjustsFontForContentSizeCategoryproperty of UILabel to true. Here is an example:</p><pre>descriptionLabel.adjustsFontForContentSizeCategory = true</pre><h3>Exercise #2</h3><p>Similar to exercise #1, this exercise is about bug fixing. Assuming you have tested the app for Dynamic Type, you should notice that the app doesn’t work great for all font sizes. Here are the issues when you set the font size to maximum:</p><ol><li>In the main screen, the address is truncated when the font is enlarged.</li><li>If the text is too long, the type label in the detailed view is truncated</li><li>For iPad, the restaurant name in the detailed view cannot be fully displayed if the name is too long.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-zP-m2DMGrRZKKnd0TVqw.png" /><figcaption><em>Figure 15–18. A few issues when the font becomes larger</em></figcaption></figure><p>Based on what you have learned, try to fix all these issues. One of the issues is related to auto layout. You will need to alter a constraint specifically for the iPad devices.</p><h3>Summary</h3><p>In this chapter, you’ve learned how to customize the navigation bar and status bar. I have also covered Dynamic Color and Dynamic Type, which allows your users to choose their preferred font size. Apple encourages all iOS developers to adopt this technology because this gives your users a choice. For people with less acute vision, they probably prefer a larger text size. For some people, they may prefer a smaller text size. Whenever possible, try your best to support Dynamic Type in your apps.</p><p>For your reference, you can download the Xcode project (including the solution to exercise) from</p><p><a href="https://drive.google.com/drive/folders/1HKIC8zaVJiZT0R-_ma_SYSC_YBwz70FL?usp=share_link">FoodPin-4 - Google Drive</a></p><pre>Reference: Apple&#39;s iOS Human Interface Guidelines (https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41007cb8fb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11 - Detail View Enhancement, Custom Fonts, and Self Sizing Cells]]></title>
            <link>https://medium.com/@thanhtra.sqcb/11-detail-view-enhancement-custom-fonts-and-self-sizing-cells-f46721a7deaa?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/f46721a7deaa</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 12:28:05 GMT</pubDate>
            <atom:updated>2023-03-02T12:28:05.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3P9NIPAOuVU1ENRctBpPw.png" /></figure><p>The detail view is a bit primitive. Wouldn’t it be great to improve the detail view to the one shown above? In this chapter we’ll focus on three areas:</p><ul><li>Design the detail view of the FoodPin app using a custom table view.</li><li>Learn how to use your own fonts.</li><li>Learn how to automatically resize a table view cell to fit its content.</li></ul><p>We will cover a lot of materials in this chapter. You will probably need several hours to work on the project. I suggest you set aside other stuff and let yourself focus on it. On top of that, I assume you already understand how to build a custom table using prototype cells. If you forget what it is, go back and read chapter 9 again.</p><p>If you are ready, let’s begin to tweak the detail view to make it look great.</p><p>What we’re going to do is to present the restaurant information including name, type, location, phone and description in a well-designed table view. The restaurant image will be used as the header of the table.</p><h3>Familiarize with the Starter Project</h3><p>To begin, first download the FoodPin project from</p><p><a href="https://drive.google.com/drive/folders/1MQWngyLF-b7yxi4ryM00WeHESFqfXog8?usp=share_link">FoodPin (2) - Google Drive</a></p><p>The project was based on what we have completed in the previous chapter but I have modified the Restaurantstruct to include two additional properties:</p><ul><li>phone</li><li>description</li></ul><p>The initialization of the restaurants array has been updated. If you look into the code in RestaurantTableViewController.swift, you should find that the values of the location property are updated with the full address. Also, it includes some dummy phone numbers and description like this:</p><pre>var restaurants:[Restaurant] = [<br>    Restaurant(name: &quot;Cafe Deadend&quot;, type: &quot;Coffee &amp; Tea Shop&quot;, location: &quot;G/F, 72 Po Hing Fong, Sheung Wan, Hong Kong&quot;, phone: &quot;232-923423&quot;, description: &quot;Searching for great breakfast eateries and coffee? This place is for you. We open at 6:30 every morning, and close at 9 PM. We offer espresso and espresso based drink, such as capuccino, cafe latte, piccolo and many more. Come over and enjoy a great meal.&quot;, image: &quot;cafedeadend&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Homei&quot;, type: &quot;Cafe&quot;, location: &quot;Shop B, G/F, 22-24A Tai Ping San Street SOHO, Sheung Wan, Hong Kong&quot;, phone: &quot;348-233423&quot;, description: &quot;A little gem hidden at the corner of the street is nothing but fantastic! This place is warm and cozy. We open at 7 every morning except Sunday, and close at 9 PM. We offer a variety of coffee drinks and specialties including lattes, cappuccinos, teas, and more. We serve breakfast, lunch, and dinner in an airy open setting. Come over, have a coffee and enjoy a chit-chat with our baristas.&quot;, image: &quot;homei&quot;, isFavorite: false),<br><br>      ...<br><br>]</pre><p>In the storyboard of the starter project, all the subviews of the detail view controller have been removed. We no longer use those views because we are going to redesign it.</p><p>These are the changes that I have prepared for you in the starter project. After you download the project, I encourage you to run it once and familiarize with the changes.</p><h3>Using Custom Fonts</h3><p>The San Francisco font was introduced in Nov 2014 and has been used as the default font in iOS apps. What if you find an open source font on Google Fonts (<a href="https://fonts.google.com/">https://fonts.google.com</a>) and want to use it in your app? How can you do it?</p><p>Xcode has made it very easy for developers to use custom fonts. All you need is just add the custom font files into your Xcode project. Let’s say, you prefer to use Nunito in your app. You can go up to <a href="https://fonts.google.com/specimen/Nunito">https://fonts.google.com/specimen/Nunito</a>. Click <em>Download Family</em> to download the font files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-mu03yaQISlq8kRSoN1kw.png" /><figcaption><em>Figure 14–1. Downloading your preferred Google fonts</em></figcaption></figure><p>Now go back to Xcode and open the starter project (if you haven’t). In the project navigator, right click the <em>FoodPin</em> folder and select <em>New Group</em>. Name the group <em>Resources</em>. Next, right click the <em>Resources</em> folder and select <em>New Group</em> to add a sub group. Name the sub group <em>Fonts</em>. Select <em>Nunito-Regular.ttf</em> and <em>Nunito-Bold.ttf</em>, and add them to the <em>Fonts</em> group. In case if you want to use all the font styles, you can add all the font files to the group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37bTtnSoIEZY59WEk0Avmw.png" /><figcaption><em>Figure 14–2. Adding the fonts file to the Xcode project</em></figcaption></figure><pre>Note: Is it a mandate to create a sub group? No, it is my practice to organize resource files like that.</pre><p>Once you dropped the files into the group, you will be prompted with the dialog as shown in figure 14-3. Make sure you check the <em>Copy items if needed</em> option and the <em>FoodPin</em> target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIoTzKU4zcDJVXc7J86qJw.png" /><figcaption><em>Figure 14–3. Select copy item if needed and the target</em></figcaption></figure><p>Once you hit <em>Finish</em>, the font files will appear in the project navigator. To ensure your app can use the font files, hold command key to select all the fonts files. In the File inspector, make sure the <em>FoodPin</em> option under target membership is enabled. If not, tick the option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWcsNd5oBRXBkqG3lybuiQ.png" /><figcaption><em>Figure 14–4. Select the FoodPin option under Target Membership</em></figcaption></figure><p>That’s the procedures to install a custom font. Later you will be able to use the <em>Nunito</em> font when we design the detailed view.</p><h3>Designing the Table View Header</h3><p>Now let’s start to design the detail view. Figure 14–5 shows the expected design of the detail screen. There are multiple ways to implement this kind of screen. One way is to use a dynamic table view to realize it. You have learned what a dynamic table view is. In earlier chapters, you created a custom table view with prototype cells. The prototype cell is similar to a design template. Though the cell’s data differs, the look &amp; feel of each cell is exactly the same. That’s the idea of prototype cells.</p><p>As you know, it is not a mandate to design a table view using one prototype cell. We have already created two prototype cells for the restaurant table view. To create the detailed screen, we will create a couple of prototype cells. The other thing I haven’t mentioned so far is that each table view has its own header view. This header view resides on top of the table cells. The header view is empty by default, but you are allowed to add your own view to that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TisTzBdKyHtx0qPWX-shA.png" /><figcaption><em>Figure 14–5. Breaking down the detail view into different cells</em></figcaption></figure><p>So, here is what we are going to do to realize the detail view design:</p><ol><li>Create a table header view that displays the restaurant image, name, type, and the heart image.</li><li>Create two prototype cells for the restaurant information:</li></ol><ul><li><strong>Prototype cell #1</strong> — for displaying a paragraph of text.</li><li><strong>Prototype cell #2</strong> — for displaying two columns of information. In the detailed view, we use this prototype cell to display the restaurant’s address and phone number.</li></ul><p>Now that you should have some ideas about how we structure the table view, let’s dive into Interface Builder and design the view.</p><p>Go to the Main storyboard of the starter project. Open the Object library and select a table view object (<em>note: it&#39;s a table view instead of a table view controller</em>). Drag it to the detail view controller. Resize it to fit the whole view and then click &quot;Add new constraints&quot;. Set the value of the <em>top</em>, <em>left</em>, <em>right</em>, and <em>bottom</em> sides to 0. And, click Add 4 constraints. This ensures the table always fits the whole screen regardless of the screen size. Your screen should look like that in figure 14-6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqtqOZ1PVToXl_8joMY-BQ.png" /><figcaption><em>Figure 14–6. Adding a table view to the detail view controller</em></figcaption></figure><p>Select the table view and set the prototype cells to 2 in the Attributes inspector. This adds two prototype cells in the table view. We will deal with the prototype cells later.</p><p>Now, add a view from the object library to the table view’s header. To locate the view object, you can search for UIView. In the document outline view, drag the view to table view and place it right above the first table view cell. Change the height of the view to 445 points in the Size inspector. This view serves as the container view holding other elements (e.g. image view) which we will add later. Once done, the design of your detail view should look like that in figure 14-7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJLqdtqRz6lHkWgeVG4VVg.png" /><figcaption><em>Figure 14–7. A view has been added to the table view’s header</em></figcaption></figure><p>You can rename the view from View to Header View in the document outline. Just click on View and change it accordingly. This step is completely optional. However, by giving each view a meaningful name, it will make you easier to identify a specific view later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-hKuDbZu98vZseImcREng.png" /><figcaption><em>Figure 14–8. Changing the name of the view</em></figcaption></figure><p>We haven’t designed the header view yet. Now drag an image view from the Object library and place it in header view. In the Attributes inspector, change the <em>Content Mode</em> to Aspect Fill. Again, to organize our UI components better, give the image view a proper name in document outline. Set it to Header Image View.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKlxB6s5ag2Zk3Dh847AHA.png" /><figcaption><em>Figure 14–9. Adding an image view to the header view</em></figcaption></figure><p>You do not need to add auto layout constraints for the header view because it is added as the table view header. However, we have to define some constraints for the header image view. The image view should always fit the size of the header view. To make this possible, we will define four spacing constraints for the top, bottom, left and right sides of the image view. Select the image view and click the <em>Add new constraints</em> button of the layout bar. Set the spacing of the top, left, right and bottom side to 0. Make sure the bars are in solid red and the <em>Constrain to margins</em>option is unchecked. Then hit the <em>Add 4 Constraints</em> button to add the constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yvQsragUDpcEOAUz4kigQ.png" /><figcaption><em>Figure 14–10. Adding layout constraints for the image view</em></figcaption></figure><p>Next, add a label and place it near the lower left corner of the image view. This label is used to display the restaurant name. Make sure the label is selected and go to the Attributes inspector. Change the color to white and set the <em>Font</em> to <em>Title 1</em> text style. Also, change its text to Name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUpkRGoysgiC9PRWKWT5fA.png" /><figcaption><em>Figure 14–11. Add a new label to the header view</em></figcaption></figure><p>Now drag another label and place it under the previous label object. This new label is used for presenting the restaurant type. In the Attributes inspector, set the background color to <em>black</em>. For the font color, change it to <em>white</em>. Change the font style to headline. Also, change the alignment option to <em>center</em>. Lastly, change its text to Type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fLjwcqB-cUs4dANiBGk9Dg.png" /><figcaption><em>Figure 14–12. Adding the type label</em></figcaption></figure><p>Next, drag a new button from the Object library and put it at the top right corner of the header view. This is an image button that allows users to mark the restaurant as favorite. In the Attributes inspector, set its title to <em>blank</em> and image to heart, which is a SF symbol. To resize the <em>heart</em> symbol, change the <em>configuration</em> option in the Default Symbol Configuration section and set it to Point Size. Increase the <em>point size</em> to 30 points to make the heart icon larger. As a final touch, change the button&#39;s tint color to <em>white</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiCLVjNL5IRCid0onyCxyw.png" /><figcaption><em>Figure 14–13. Adding a button for the heart icon</em></figcaption></figure><p>Now it’s time to add some layout constraints for these components. Let’s first start with the heart button. I want to define the following layout requirement for it:</p><ul><li>The size of the button should be fixed</li><li>The top side of the label should be 10 points away from margin of the header view.</li><li>The right (or trailing) side of the label should be 10 points away from margin of the header view.</li></ul><p>Select the heart button and then click the <em>Add new constraints</em> button. Set the values of both top and right sides to 10 points. Please make sure the <em>Constrain to margins</em> option is checked. Next, check both width and height options to enable the size constraints. Lastly, click the <em>Add 4 Constraints</em> button to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7D64hyfdRPJE65Zw9BVrAw.png" /><figcaption><em>Figure 14–14. Adding layout constraints for the heart button</em></figcaption></figure><p>Next, let’s add the layout constraints for the name and type labels. We will first embed both labels in a stack view. Select both labels in the document outline. Click the <em>Embed in</em> button and choose <em>Stack view</em> to embed both labels in a stack view. Once you created the stack view, go to the Attributes inspector and set the spacing value to 10 points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTEibUhCZFMU8IsLiJDP1Q.png" /><figcaption><em>Figure 14–15. Embedding both labels in a stack view</em></figcaption></figure><p>Now it’s for the layout requirement. I want to keep the stack view at the lower left corner of the header view, so we will add a few spacing constraints. Select the stack view and click the <em>Add new constraints</em> button. Set the left, right, and bottom value to 20, 20, and 150 points respectively. You are free to adjust these values if you want to change the position of the stack view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XDN_Fx-V2uykKqdFl4cMA.png" /><figcaption><em>Figure 14–16. Adding spacing constraints for the stack view</em></figcaption></figure><p>That’s it! We’ve completed the design of the header view. Now let’s move onto the coding part. We will create a class for the header view. In project navigator, right-click the <em>View</em> folder and select <em>New File…</em>. Choose the <em>Cocoa Touch Class</em> template and hit <em>Next</em>. Set the class name to RestaurantDetailHeaderView and its subclass to UIView. Click <em>Next</em> to create the file.</p><p>Edit the RestaurantDetailHeaderView.swift file like below to add the required outlet variables:</p><pre>import UIKit<br><br>class RestaurantDetailHeaderView: UIView {<br><br>    @IBOutlet var headerImageView: UIImageView!<br>    @IBOutlet var nameLabel: UILabel!<br>    @IBOutlet var typeLabel: UILabel!<br>    @IBOutlet var heartButton: UIButton!<br><br>}</pre><p>Go back to Interface Builder and select the <em>Header View</em> in document outline. In Identity inspector, change the custom class to RestaurantDetailHeaderView. Next, establish a connection with each of the corresponding outlet variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAGprIgusYZA72E2yHXncQ.png" /><figcaption><em>Figure 14–17. Establishing the connections</em></figcaption></figure><p>Now that the header view is ready for us to populate the restaurant data, it is time to modify RestaurantDetailViewController.swift. In the RestaurantDetailViewController class, insert two new outlet variables for the table view and the header view. Later, we need to modify their content in code. This is why we need to create these outlets:</p><pre>@IBOutlet var tableView: UITableView!<br>@IBOutlet var headerView: RestaurantDetailHeaderView!</pre><p>Next, update the viewDidLoad method with the following code:</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br><br>    navigationController?.navigationBar.prefersLargeTitles = false<br><br>    // Configure header view<br>    headerView.nameLabel.text = restaurant.name<br>    headerView.typeLabel.text = restaurant.type<br>    headerView.headerImageView.image = UIImage(named: restaurant.image)<br><br>    let heartImage = restaurant.isFavorite ? &quot;heart.fill&quot; : &quot;heart&quot;<br>    headerView.heartButton.tintColor = restaurant.isFavorite ? .systemYellow : .white<br>    headerView.heartButton.setImage(UIImage(systemName: heartImage), for: .normal)<br><br>}</pre><p>The code is very straightforward. When the detail view is loaded, we set the restaurant data to the corresponding label or image view. We also check the isFavorite property of the selected restaurant and change the color of the heart icon. To make the code work, don&#39;t forget to connect the outlets with the corresponding UI components. The tableView outlet should be connected with the <em>Table View</em> of the detail view controller and the headerView outlet should be connected with <em>Header View</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbq0Sdg-TjHS1zfUpKcFMg.png" /><figcaption><em>Figure 14–18. Establishing the connections for both header view and table view</em></figcaption></figure><p>After all the tedious procedures, it is now ready to test your app! Run the project and have a quick look. The image is now displayed in the table view’s header (right above the rest of the table rows).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0rxkFavljWyqPakrcixDA.png" /><figcaption><em>Figure 14–19. Displaying the restaurant in the header view</em></figcaption></figure><h3>Understanding Image View Scaling</h3><p>Earlier, I asked you to set the content mode of the image view to <em>Aspect Fill</em>. We haven’t discussed how this content mode option affects the presentation of the image. Before we continue to build the detailed view, let me explain the usage of this option. Every view in iOS has a content mode. The UIImageView class is a subclass of UIView, so it also has a content mode property to specify how a view adjusts its content. Here are the three common scaling modes you usually use:</p><ul><li>Scale to Fill (default)</li><li>Aspect Fit</li><li>Aspect Fill</li></ul><p>By default, the UIImageView object is set to <em>Scale To Fill</em> . In this mode, the image view scales its image to fit the view&#39;s size. The aspect ratio of the image may be changed due to the scaling. If you change the mode to <em>Aspect Fit</em>, the aspect ratio of the image will be maintained. However, it may leave some extra spaces on both sides of the image if the image view&#39;s aspect ratio is different from that of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDnEBHVJkw43T2MeWpapJA.png" /><figcaption><em>Figure 14–20. Image View Scaling Mode</em></figcaption></figure><p>The <em>Aspect Fill</em> mode is the best fit for our design, which is why we set the header image view to this mode. In this mode, the image view scales the image to fill the size of the view. The aspect ratio is maintained, though some parts of the image may extend over the edges of the image view. In this case, you will need to enable an option called <em>Clip to Bounds</em> to cut off the extra parts (see figure 14–20).</p><p>In Xcode 14, the <em>Clip to Bounds</em> option is enabled by default. This is why the <em>Aspect Fill</em> mode works out of the box. You can select the image view and check the <em>Clips to Bounds</em> setting in the Attributes inspector.</p><h3>Fixing a Couple of Issues</h3><p>The header view looks great, right? However, there are a couple issues we need to fix:</p><ol><li>For some lengthy restaurant names, they cannot be fully displayed.</li><li>For some restaurant images with a lot of white backgrounds, the restaurant name may be clearly shown.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9156iXa8WVGygBFoEqpXg.png" /><figcaption><em>Figure 14–21. A couple of the issues with the current header view</em></figcaption></figure><h4>Truncated Restaurant Names</h4><p>The first issue is related to the restaurant name. If the name is too long, the label will truncate the text. By default, the label is set to display text in a single line. You can select the label and then reveal the <em>Lines</em> option in the Attributes inspector. The current value should be set to 1.</p><p>Labels in iOS are capable to display multiple lines. All you need is to change the value to 0. In this case, the label will automatically determine the total number of lines to fit its content. While you can change the value in Interface Builder, I prefer to customize the property of the label in code. Open RestaurantDetailHeaderView.swift and edit the nameLabel variable to update the numberOfLines property using didSet:</p><pre>@IBOutlet var nameLabel: UILabel! {<br>    didSet {<br>        nameLabel.numberOfLines = 0<br>    }<br>}</pre><h4>Dimming the Image Using UIView</h4><p>Now let’s fix the second issue. Since the restaurant name label is in white, it may not be shown clearly if the restaurant image has a lot of white in it. How can we solve this issue?</p><p>One way is to add an overlay to dim the image. To do that, go to Main. Open the Object library, drag a view and place it right below the header image view in document outline. Name it <em>Dim View</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uo8GOn_nutTXue8KZuywxQ.png" /><figcaption><em>Figure 14–22. Adding a new view</em></figcaption></figure><p>Resize the view to make it the same size as the header view. Then go to the Attributes inspector. Set the background color to black and alpha value to 0.2. The alpha value controls the transparency of the color. It goes from 0 to 1 where 0 is completely transparent and 1 fully opaque. We set the value to 0.2 so that it is partially transparent, and achieve a dimming effect. If you don&#39;t know how to change the opacity value, you can choose <em>Custom</em> in the <em>Background</em>option. Then you will see a Colors dialog. Choose the <em>Color Sliders</em> tab and set to <em>RGB Sliders</em>. You can then choose the opacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rr6PBJf81775P03EwEL41A.png" /><figcaption><em>Figure 14–23. Changing the background color and setting the opacity</em></figcaption></figure><p>Lastly, don’t forget to define the layout constraint for the view. Select the Dim View and click the <em>Add new constraints</em> button. Set the spacing of the top, left, right and bottom side to 0. Make sure the bars are in solid red and the <em>Constrain to margins</em> option is unchecked. Then hit the <em>Add 4 Constraints</em> button to add the constraints.</p><p>Now it is time to test the header view again. If you got everything correct, the header view should have fixed the mentioned issues. With the <em>Dim View</em>, we increase the color contrast of the image and the text. The restaurant name is now clearly shown even in light background. And, the name label automatically wraps the text onto a new line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b00PQ4hF0eiDGoPzEfpk9A.png" /><figcaption><em>Figure 14–24. The image is now dimmed</em></figcaption></figure><h3>Using Custom Fonts for Dynamic Types</h3><p>Do you still remember the fonts files we imported at the very beginning of the chapter? We haven’t used them yet. Right now, all the labels are configured to use text styles. For example, the name label uses the <em>Title 1</em> text style. Without any customizations, iOS uses San Francisco as the default font.</p><p>To use a custom font for text style (or Dynamic Types), we first have to configure those font files in Info.plist, which is the configuration of the Xcode project. In the project navigator, select Info.plist and right-click any blank area to open the context menu. Select <em>Add row</em> to create a new row in the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8B2Jdud9lafNj9ln8JbLg.png" /><figcaption><em>Figure 14–25. Editing the Info.plist file</em></figcaption></figure><p>Next, type <em>Fonts provided by application</em> in the Key field. In order to register the font files, we need to add the key and specify all the font files. Once you add the key, click the disclosure button to expand it. For item 0, set its value to Nunito-Regular.ttf. You can click the + button of item 0 and add another item. For item 1, set the value to Nunito-Bold.ttf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5_Xz6TJwY1BQhQ7RcYBmw.png" /><figcaption><em>Figure 14–26. Specifying the font files in Info.plist</em></figcaption></figure><p>Now you are ready to use the fonts in Interface Builder or using code. To change the font of a specified text style, you can write the code like this:</p><pre>if let customFont = UIFont(name: &quot;Nunito-Bold&quot;, size: 40.0) {<br>    nameLabel.font = UIFontMetrics(forTextStyle: .title1).scaledFont(for: customFont)<br>}</pre><p>The UIFont class lets you load the font file and provides you with access to the font’s characteristics. You use a UIFontMetrics object to support scalable custom fonts in your app. In the code above, we apply the Nunito-Bold font to the <em>Title1</em> text style. If you want to set the custom font for another text style, just pass the forTextStyle parameter with another value.</p><p>Now modify both nameLabel and typeLabel in the RestaurantDetailHeaderView class like this:</p><pre>@IBOutlet var nameLabel: UILabel! {<br>    didSet {<br>        nameLabel.numberOfLines = 0<br><br>        if let customFont = UIFont(name: &quot;Nunito-Bold&quot;, size: 40.0) {<br>            nameLabel.font = UIFontMetrics(forTextStyle: .title1).scaledFont(for: customFont)<br>        }<br>    }<br>}<br>@IBOutlet var typeLabel: UILabel! {<br>    didSet {<br>        if let customFont = UIFont(name: &quot;Nunito-Bold&quot;, size: 20.0) {<br>            typeLabel.font = UIFontMetrics(forTextStyle: .headline).scaledFont(for: customFont)<br>        }<br>    }<br>}</pre><p>We tell the system to use our own font for both name and type labels. Once you made the change, you can run the app again. In the detailed view, the app should now use the custom font.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8auc3Xd-mdNG2qXlh6PGRQ.png" /><figcaption><em>Figure 14–27. Using the custom font for both labels</em></figcaption></figure><h3>Designing the Prototype Cells</h3><p>Now that we’ve completed the implementation of the header view, let’s move to the implementation of the table view cells. If you read the book from the very beginning, you should know how to customize the prototype cell. To display the restaurant information, we will create two prototype cells to support two different types of cell layout. One prototype cell is designed to display the multiline text. The other cell is for displaying two column data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rr0LLvASstUfN5iFcpNnkw.png" /><figcaption><em>Figure 14–28. Creating two prototype cells</em></figcaption></figure><h4>RestaurantDetailTextCell</h4><p>Now open the Main storyboard and drag a label object to the first prototype cell. Double click the label and change its title to <em>Description</em>. Go to the Attributes inspector and change the font to the <em>Body</em> text style. Then click the <em>Add new constraints</em> button to add four spacing constraints. Set the spacing value to 0 for all sides and make sure you check the <em>Constrain to margins</em> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRG9zFt_HxnxuBvXICqO5Q.png" /><figcaption><em>Figure 14–29. Designing the first prototype cell with a label</em></figcaption></figure><p>For each prototype cell, we will create a corresponding Swift file to connect with it. In project navigator, right click <em>View</em> folder and choose <em>New file…</em>. Select the <em>Cocoa Touch Class</em> template. In the next screen, name the class RestaurantDetailTextCell and set it as a subclass of UITableViewCell. Click <em>Next</em> to save the file.</p><p>Similarly to what we have done before, we will create an outlet variables for the connections of the label. Declare the following variables in the RestaurantDetailTextCell.swift file:</p><pre>@IBOutlet var descriptionLabel: UILabel! {<br>    didSet {<br>        descriptionLabel.numberOfLines = 0<br>    }<br>}</pre><p>You should understand the code above. We just create an outlet for the text label. Since the text is going to extend over multiple lines, we set the label’s numberOfLines property to 0.</p><p>Now go back to Interface Builder and select the prototype cell we just designed. We haven’t set the cell identifier and custom class. So, go to the Attributes inspector and set the identifier to RestaurantDetailTextCell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QjkPxkL2KVF3-5DpDSvvw.png" /><figcaption><em>Figure 14–30. Setting the cell’s identifier</em></figcaption></figure><p>To set the custom class, go to the Identity inspector and change the custom class to RestaurantDetailTextCell.</p><p>Did you notice that the identifier and the class name are the same? I will explain why I did that in a while. Now, right click RestaurantDetailTextCell in the document outline. Establish the connections between the description label and the outlet variable we defined earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWlbdX2gAIO5gagpq4-Ghw.png" /><figcaption><em>Figure 14–31. Setting the cell’s identifier</em></figcaption></figure><h4>RestaurantDetailTwoColumnCell</h4><p>Now we will move onto the implementation of the second prototype cell. This cell is designed to display two columns of data. Obviously, we will make use of stack views to create the layout.</p><p>First, make the second prototype cell a little bit taller (say, 140 points). This would let us easier fill the UI components in the cell. Now drag a label to the cell and change the text to Address. In the Attributes inspector, set its font style to Headline. Next, drag another label to the cell and place it right below the <em>Address</em> label. Name the label Full Address and set its font style to Body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pkupBnu5o4R0-Y18aPIqg.png" /><figcaption><em>Figure 14–32. Adding two labels to the second prototype cell</em></figcaption></figure><p>Once you configured the two labels, hold command key and select both items. Click <em>Embed in</em>and choose <em>Stack view</em> to embed both labels in a vertical stack view (see figure 14–32). In the Attributes inspector, change the stack view’s distribution option to Equal Spacing and its spacing value to 8.</p><p>We will duplicate the stack view to create the second column. You can use copy-and-paste to duplicate the view. Alternatively, you can hold the <em>Option</em> key and drag the stack view to duplicate one. For the new stack view, change both labels to Phone and Phone Numberrespectively.</p><p>To arrange both stack views side by side, select both stack views and click <em>Embed in</em>. Choose stack view to embed them in a horizontal stack view. For the new stack view, set its alignment to Top because we want to align the text to the top of the view. Also, change the distribution option to Fill Equally and set its spacing to 10. Your stack view should look similar to the one shown in figure 14-33.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ai4TAYkNL7CBR3HZTZw1vg.png" /><figcaption><em>Figure 14–33. Embed the two stack views into a horizontal stack view</em></figcaption></figure><p>Now, we will add a few spacing constraints for the stack view. Select the new stack view and click <em>Add new constraints</em>. Set the spacing value for all sides to 0 and tick the <em>Constrain to margins</em>option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdEQAPexXQbrhZpzjoj7mQ.png" /><figcaption><em>Figure 14–34. Adding spacing constraints</em></figcaption></figure><p>Currently, the height of the cell is fixed. To make the cell adaptable to variable height, select the table view cell in document outline. Go to the Size inspector and delete the preset row height.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VQXZkbDqLO1_fOhRe7V-g.png" /><figcaption><em>Figure 14–35. Set the cell’s size to automatic</em></figcaption></figure><p>Now that we have completed the design of the second prototype cell, the next step is to create a Swift file to pair with this cell. In project navigator, right click the <em>View</em> folder and choose <em>New File…</em>. Choose the <em>Cocoa Touch Class</em> template and click the <em>Next</em> button. Name the class RestaurantDetailTwoColumnCell and set its subclass to UITableViewCell.</p><p>Once created, open the RestaurantDetailTwoColumnCell.swift file. Declare the outlet variables for the labels:</p><pre>@IBOutlet var column1TitleLabel: UILabel! {<br>    didSet {<br>        column1TitleLabel.text = column1TitleLabel.text?.uppercased()<br>        column1TitleLabel.numberOfLines = 0<br>    }<br>}<br>@IBOutlet var column1TextLabel: UILabel! {<br>    didSet {<br>        column1TextLabel.numberOfLines = 0<br>    }<br>}<br>@IBOutlet var column2TitleLabel: UILabel! {<br>    didSet {<br>        column2TitleLabel.text = column2TitleLabel.text?.uppercased()<br>        column2TitleLabel.numberOfLines = 0<br>    }<br>}<br>@IBOutlet var column2TextLabel: UILabel! {<br>    didSet {<br>        column2TextLabel.numberOfLines = 0<br>    }<br>}</pre><p>I tried to make this prototype cell as flexible as possible, so all the four labels can be configurable using code. They are not limited to display address and phone number. It is actually suitable to display any text in two column layout.</p><p>Again, we set the numberOfLines property to 0 in order to display multiple lines. For the title labels, we have an additional line of code to convert the text to uppercase.</p><p>Go back to Main and select the second prototype cell. Go to the Attribute inspector and set the cell identifier to RestaurantDetailTwoColumnCell. In the Identity inspector, set the custom class to RestaurantDetailTwoColumnCell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrnnU91QGA4aHKAY0MNZkg.png" /><figcaption><em>Figure 14–36. Setting the custom class of the 2-column prototype cell</em></figcaption></figure><p>Finally, establish a connection between the labels and the outlet variables. The column1TitleLabel should be connected to the <em>ADDRESS</em> label and the column1TextLabel should be connected to <em>Full Address</em>. For the <em>PHONE</em> label, it should be connected to the column2TitleLabel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSf5j56uk-oq3EjkRHUUlg.png" /><figcaption><em>Figure 14–37. Setting the custom class of the 2-column prototype cell</em></figcaption></figure><h3>Updating the RestaurantDetailViewController Class</h3><p>Great! You will finished the design of the prototype cells. Let’s update the RestaurantDetailViewController class to populate the restaurant information. The RestaurantDetailViewController class is a subclass of UIViewController. As you&#39;ve learned in chapter 8, we have to adopt both the UITableViewDataSource and UITableViewDelegateprotocols for displaying content in the table view.</p><p>In the earlier chapter, we learned to adopt the protocols with the following syntax:</p><pre>class RestaurantDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {</pre><p>You append the required protocols after the super class. This is one of the ways to adopt protocols in Swift. Let me take this chance to show you another approach by using a Swift feature known as Extensions. Extensions allow you to extend the functionalities of an existing class and structure. To create an extension, you start with the keyword extension followed by the class you want to extend. For example, to adopt the UITableViewDataSource and UITableViewDelegate protocols in the RestaurantDetailViewController class, you can create an extension like this:</p><pre>extension RestaurantDetailViewController: UITableViewDataSource, UITableViewDelegate {<br>     .<br>     .<br>     .<br>}</pre><p>Now let’s open the RestaurantDetailViewController.swift file and write the extension. Insert the following code at the end of the file:</p><pre>extension RestaurantDetailViewController: UITableViewDataSource, UITableViewDelegate {<br><br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return 2<br>    }<br><br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        switch indexPath.row {<br>        case 0:<br>            let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RestaurantDetailTextCell.self), for: indexPath) as! RestaurantDetailTextCell<br><br>            cell.descriptionLabel.text = restaurant.description<br><br>            return cell<br><br>        case 1:<br>            let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RestaurantDetailTwoColumnCell.self), for: indexPath) as! RestaurantDetailTwoColumnCell<br><br>            cell.column1TitleLabel.text = &quot;Address&quot;<br>            cell.column1TextLabel.text = restaurant.location<br>            cell.column2TitleLabel.text = &quot;Phone&quot;<br>            cell.column2TextLabel.text = restaurant.phone<br><br>            return cell<br><br>        default:<br>            fatalError(&quot;Failed to instantiate the table view cell for detail view controller&quot;)<br><br>        }<br>    }<br><br>}</pre><p>We created an extension for RestaurantDetailViewController, adopted the protocols, and implemented the required method for populating the table view&#39;s data. The detail view has two rows of data. This is why we return 2 in the tableView(_:numberOfRowsInSection:) method.</p><p>The implementation of the tableView(_:cellForRowAt:) method is a bit different from what you learned before because we now have to cater for two different types of prototype cells. The first cell uses RestaurantDetailTextCell, while the second one uses RestaurantDetailTwoColumnCell.</p><p>In the code above, we use switch to control the program flow and execute different branches of code depending on the value of indexPath.row. For the first cell (i.e. indexPath.row is 0), we dequeue the reusable cell with the identifier RestaurantDetailTextCell and then populate the restaurant description.</p><p>Recall that we set the cell’s identifier to its custom class name, you can explicity specify the identifier and dequeue the cell like this:</p><pre>let cell = tableView.dequeueReusableCell(withIdentifier: &quot;RestaurantDetailTextCell&quot;, for: indexPath) as! RestaurantDetailIconTextCell</pre><p>The result of the code above is exactly the same as the one we wrote earlier. The code String(describing: RestaurantDetailTextCell.self) will return you the name of the class (i.e. RestaurantDetailTextCell).</p><pre>let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RestaurantDetailTextCell.self), for: indexPath) as! RestaurantDetailTextCell</pre><p>So, why do we use the latter version? Hardcoding the cell’s identifier is prone to typos. Xcode will not show you any errors even if you type the identifier wrongly. You can only reveal the error when running the app.</p><p>By using the latter version, if we wrongly type the class name (say, RestaurantDetailTxtCell.self), Xcode will immediately prompt you the error.</p><p>For case 1, the code is very similar but we use the RestaurantDetailTwoColumnCell for displaying the address and phone number.</p><p>The case default will be executed only if the value of indexPath.row doesn&#39;t match 0 or 1. In this case, we give a fatal error.</p><p>Okay, the code of the RestaurantDetailViewController class is almost ready. There is only one thing left. We haven&#39;t established the connection with the table view in the storyboard.</p><p>In earlier chapters, I showed you how to do it via Interface Builder (refer to chapter 8). This time let’s do it using code. In the viewDidLoad method of RestaurantDetailViewController, insert the following lines of code:</p><pre>tableView.delegate = self<br>tableView.dataSource = self</pre><p>That’s it. We set the table view’s delegate and dataSource to self.</p><h3>Ready to Test</h3><p>Hit the Run button and test your app. The detail view now displays more information about the selected restaurant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LR_YueCwFfFnJYMLYAWJ8g.png" /><figcaption><em>Figure 14–38. Detail view of some sample restaurants</em></figcaption></figure><h3>Customizing the Table View Separator</h3><p>The table view is now pretty nice. If you want to remove the separator of the table, you can insert the following line in the viewDidLoad method of RestaurantDetailViewController:</p><pre>tableView.separatorStyle = .none</pre><p>By setting the style of the separator to .none, you can remove all the separators.</p><h3>Understanding Self Sizing Cells</h3><p>Before we end this chapter, let me talk about the concept of self sizing cells. Have you ever wondered why the cell’s height is automatically adjusted? When the description / location has more text, the height of the cell will be increased accordingly.</p><p>Prior to iOS 8, if you want to display dynamic content in a table view with multiple rows, you have to calculate the row height of a cell manually. Later in iOS 8, Apple introduced a new feature for UITableView known as <em>Self Sizing Cells</em>.</p><p>In brief, to enable self sizing of a table view cell, you have to implement a few things:</p><ol><li>Define auto layout constraints for the prototype cell.</li><li>Specify the estimatedRowHeight property of the table view.</li><li>Set the rowHeight property of the table view to UITableViewAutomaticDimension.</li></ol><p>Before iOS 11, you have to manually handle point 2 and 3. Now Xcode sets both the estimated row height and row height to automatic by default (see figure 14–35). Therefore, to use self sizing cells, all you need to do is just to define the layout constraints.</p><p>As long as you define the proper layout constraints, the cell will be resized automatically to fit its content.</p><h3>Summary</h3><p>Great! You’ve made it. I hope you love it and the app you created. You’ve already built a quite polished app. It’s not a complex app but you’ve managed to use some common components such as table view and navigation controller in iOS. What’s more is that you’ve learned how to work with custom fonts and create a detail screen using a custom table view.</p><p>I also introduced a popular feature in Swift called Extensions. This is a very powerful feature that you will utilize it in your app development. To learn more about Swift Extensions, you can check out this document (<a href="https://docs.swift.org/swift-book/LanguageGuide/Extensions.html">https://docs.swift.org/swift-book/LanguageGuide/Extensions.html</a>).</p><p>This is a huge chapter. Even if you can’t wait to proceed to the next chapter, I suggest taking a break here. It needs time to let yourself digest all the materials we discussed so far. Grab a coffee or whatever drinks you like and relax.</p><p>For reference, you can download the complete project from</p><p><a href="https://drive.google.com/drive/folders/1DUpWnDdLVqVTabgqHrfxTIfjQhSedyOp?usp=share_link">FoodPin-2 (2) - Google Drive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f46721a7deaa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 - Introduction to Navigation Controller and Segue (UIKit)]]></title>
            <link>https://medium.com/@thanhtra.sqcb/10-introduction-to-navigation-controller-and-segue-uikit-3f3c27c47d32?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f3c27c47d32</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 11:21:21 GMT</pubDate>
            <atom:updated>2023-03-02T11:21:21.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVxf6EWQXz-F3FyOtlNpng.png" /></figure><p>First things first, what’s navigation controller? Like table views, navigation controllers are another common UI components in iOS apps. It provides a drill-down interface for hierarchical content. Take a look at the built-in Photos app, YouTube, and Contacts. They all use navigation controllers to display hierarchical content. Generally, you combine a navigation controller with a stack of table view controllers to build an elegant interface for your apps. Being that said, this doesn’t mean you have to use both together. Navigation controllers can work with any types of a view controller.</p><h3>Scenes and Segues in Storyboards</h3><p>Up till now, we just lay out a table view controller in the storyboard of the FoodPin app. Storyboarding allows you to do more than that. You can add more view controllers in the storyboard, link them up, and define the transitions between them. All these can be done without a line of code. When working with storyboards, <em>scene</em> and <em>segues</em> are two of the terms you have to understand. In a storyboard, a scene usually refers to the on-screen content (e.g. a view controller). Segues sit between two scenes and represent the transition from one scene to another. <em>Push</em> and <em>Modal</em> are two common types of transition.</p><pre>Note: You can make storyboards more manageable and modular by using a feature called storyboard references. When your project becomes large and complex, you can break a large storyboard into multiple storyboards and link them up using storyboard references. This feature is particularly useful when you are collaborating with your team members to create a storyboard.</pre><h3>Creating Navigation Controller</h3><p>We’ll continue to work on the Food Pin app by embedding the table view controller into a navigation controller. When a user selects any of the restaurants, the app navigates to the next screen to display the restaurant details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-4CHCwni68EetuzA6FYFw.png" /><figcaption><em>Figure 13–1. FoodPin app with a navigation bar in dark mode</em></figcaption></figure><p>If you’ve closed the FoodPin project</p><p>(<a href="http://www.appcoda.com/resources/swift57/FoodPinTableDeletion.zip">http://www.appcoda.com/resources/swift57/FoodPinTableDeletion.zip</a>)</p><p>it is time to fire up Xcode and open the project again. Select Main to switch to the Interface Builder editor. Xcode provides an <em>embed</em> feature that makes it easy to embed any view controller in a navigation controller. Select the table view controller and click <em>Editor</em> in the menu. Choose <em>Embed in &gt; Navigation Controller</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2j5NF2gHt5OAnjgUNeeBPw.png" /><figcaption><em>Figure 13–2. Embed in option in Xcode menu</em></figcaption></figure><p>Xcode automatically embeds the controller in a navigation controller. Let’s set the title of the navigation bar. Select the navigation bar of the table view controller. Under the Attributes inspector, change the value of the title to <em>FoodPin</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0uOSOsGW2NtVrMcGDDiug.png" /><figcaption><em>Figure 13–3. Embedding the table view controller in a navigation controller</em></figcaption></figure><p>Now run the app and see how it looks. The app is the same as before, but added with a navigation bar.</p><h3>Large Navigation Bar Titles</h3><p>Starting from version 11, iOS comes with large navigation bar titles. The stock apps, such as Mail and Settings, use large titles in the navigation bar. The size of the bar is not fixed, however. When you scroll the content, the navigation bar shrinks back down its size to that appears in iOS 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIvh7aN_EPNj5nhoo7G5Zw.png" /><figcaption><em>Figure 13–4. Default navigation bar title in iOS (left &amp; middle), Large title enabled (right)</em></figcaption></figure><p>By default, large title is not enabled in Xcode. If you want to use large title in the navigation bar, you can insert this line of code in the viewDidLoad() method of the RestaurantTableViewController class and place it after super.viewDidLoad():</p><pre>navigationController?.navigationBar.prefersLargeTitles = true</pre><p>Test the app again, and you will see the result as shown in figure 13–4.</p><h3>Adding a Detail View Controller</h3><p>With just a few clicks and a line of code, you’ve added a navigation bar to your app with large titles. What’s missing is another view controller that displays the restaurant details. When a user selects a restaurant, the app transits to the detail view controller and displays the restaurant details. This is what we are going to do.</p><p>In Interface Builder, drag a view controller from the Object library to create the detail view controller. The primary purpose of this chapter is to show you how to implement navigation controller. We’ll keep the detail view as simple as possible. Let’s just display the restaurant photo in the detail view. Drag an Image View from the Object library to the view controller. Resize it to fit the view, and add spacing constraints for each side of the image view. To ensure the image is scaled properly, go to the Attributes inspector and change the <em>mode</em> from <em>Scale to Fill</em>to <em>Aspect Fill</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9U4KCK2CckQZjIV5OtCnw.png" /><figcaption><em>Figure 13–5. Adding an image view to the detail view controller</em></figcaption></figure><p>Now you have a table view controller and a detail view controller configured in the storyboard. The question is how can you connect them together? In storyboards, we need to connect them through a segue. In music, a segue is a seamless transition between one piece of music and another. In storyboards, the transition between two scenes is called <em>segue</em>.</p><p>The table view controller will transit to the detail scene when a user taps a cell. So, we will add a segue to connect the prototype cell and the detail scene. It’s very straightforward to add a segue object. Press and hold the control key, click on the prototype cell (i.e. datacell) and drag to the Detail View Controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDWh6T6TMtQBNZZHLL7YvA.png" /><figcaption><em>Figure 13–6. Connecting scenes with segue</em></figcaption></figure><p>Sometimes it is pretty difficult to select the prototype cell in the table view controller, I suggest you open the document outline view, and drag from the datacell to the view controller. When you release the buttons, a pop-up menu appears for you to choose the style for the segue. Select &quot;Show&quot; for the style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUt511Ns1tEhWHpoTucLyw.png" /><figcaption><em>Figure 13–7. Choosing a segue style</em></figcaption></figure><p>Once chosen, Xcode automatically connects the datacell and the detail view controller with a <em>show</em> segue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SD1rpBqQrMkhQlewHzdQ_Q.png" /><figcaption><em>Figure 13–8. Viewing a segue</em></figcaption></figure><p>Repeat the same procedures to connect the favoritecell to the view controller. You will then in another segue between the table view controller and the view controller.</p><p>In iOS, it supports the following types of segue:</p><ul><li><strong>Show</strong> — when the <em>show</em> style is used, the content is pushed on top of the current view controller stack. A back button will be displayed in the navigation bar for navigating back to the original view controller. Typically, we use this segue type for navigation controllers.</li><li><strong>Show detail</strong> — similar to the <em>show</em> style, but the content in the detail (or destination) view controller replaces the top of the current view controller stack. For example, if you select <em>show detail</em> instead of <em>show</em> in the FoodPin app, there will be no navigation bar and back button in the detail view.</li><li><strong>Present modally</strong> — presents the content modally. When used, the detail view controller will be animated up from the bottom and cover the entire screen on iPhone. A good example of <em>present modally</em> segue is the “Add” feature of the built-in Calendar app. When you click the + button in the app, it brings up a “New Event” screen from the bottom.</li><li><strong>Present as popover</strong> — Present the content as a popover anchored to an existing view. Popover is commonly found in iPad apps, and you have already implemented popover in earlier chapters.</li></ul><pre>Note: These segue types are deprecated since the release of iOS 8: Push, Modal, Popover, Replace. When you see the word &quot;deprecated&quot;, it means those functions are not recommended to use. They will probably be removed in the future version of iOS SDK.</pre><p>Now, you’re ready to run the app. Once launched, select a restaurant and the app should navigate to the detail view controller. Meanwhile, the detail view controller just shows a blank screen. The good news is that you already created a navigation interface.</p><p>Without writing a single line of code, you’ve added a navigation controller in your app. However, I guess you got a couple of questions in your mind:</p><ul><li>How can you pass the restaurant information from RestaurantTableViewController to the detail view controller?</li><li>How can you display the photo of the selected restaurant in the detail view controller?</li></ul><p>We’ll look into them one by one in a minute.</p><p>Before moving on to the next section, let’s make a little tweak. When you run the app and select a cell, it now navigates to the blank screen and shows an action sheet that we have implemented earlier. We no longer need that action sheet. Later we’ll add the same function in the detail view controller. Therefore, remove the tableView(_:didSelectRowAt:) method from RestaurantTableViewController.swift.</p><pre>Quick tip: Sometimes you may just want to comment out a block of code instead of deleting them. Xcode provides a shortcut key to comment multiple lines of code. First, select the block of code and press command+slash. Xcode automatically marks the code block with comment indicators. To remove the comment, do the same procedures again.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNPncdlyUAlc_Go4iabmtQ.png" /><figcaption><em>Figure 13–9. Use a shortcut key to comment a block of code quickly</em></figcaption></figure><h3>Creating a New Class for the Detail View Controller</h3><p>Okay, let’s go back to the detail view controller. Our goal is to update the image view in the view controller with the selected restaurant. The view controller is now associated with the UIViewController class by default. As explained before, the UIViewController class only provides the fundamental view management model. There is no variable for storing the restaurant image. We have to extend UIViewController to create our own class so that we can add a new variable for the image view.</p><p>In the Project Navigator, right-click the <em>Controller</em> folder and select <em>New File…</em>. Choose <em>Cocoa Touch Class</em> as the class template. Name the class RestaurantDetailViewController and set it as a subclass of UIViewController. Click <em>Next</em> and save the file in your project folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSjEr_SO7a97L4IVESPUeA.png" /><figcaption><em>Figure 13–10. Create a DetailViewController class</em></figcaption></figure><p>First, we have to establish a relationship between the view controller in Interface Builder and the new class. Go to Main storyboard and assign the RestaurantDetailViewController class to the detail view controller. In Interface Builder, select the view controller and open the Identity inspector. Change the custom class to RestaurantDetailViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLMgSGKBWHaHgsHtibiOHw.png" /><figcaption><em>Figure 13–11. Assign a custom class for the detail view controller</em></figcaption></figure><h3>Adding Variables to the Custom Class</h3><p>There are a couple of things we have to add in the custom class:</p><ul><li>Create a variable named restaurantImageName – when a user selects a restaurant in the table view controller, there must be a way to pass the image name to the detail view. This variable will be used for data passing.</li><li>Create an outlet called restaurantImageView for the image view – we need a reference to update the image view of the detail view controller, so we have to create an outlet.</li></ul><p>Okay, insert the following code to the RestaurantDetailViewController class:</p><pre>@IBOutlet var restaurantImageView: UIImageView!<br>var restaurantImageName = &quot;&quot;</pre><p>Next, establish a connection between the restaurantImageView variable and the image view of the detail view controller. Go back to the Main storyboard. Right click the Restaurant Detail View Controller object in the document outline. In the popover menu, connect the restaurantImageView outlet with the image view of the controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nP3KsgSvDxCRv2ABfNBWmw.png" /><figcaption><em>Figure 13–12. Establish the connection between the image view and the outlet</em></figcaption></figure><p>Now that you’ve linked up the outlet variable with the image view object in the storyboard, but there is still one thing left. You haven’t provided the image yet. The image view should display the selected restaurant image. In the viewDidLoad method of the RestaurantDetailViewController class, insert a line of code. Your method should look like this:</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    restaurantImageView.image = UIImage(named: restaurantImageName)<br>}</pre><p>The viewDidLoad method is called when the view is loaded into memory. You can provide additional customization of the view in this method. In the above, we simply set the image view&#39;s image to the selected restaurant image.</p><p>Try to compile and run your app. Oops! The detail view is still blank after selecting a restaurant. We still miss one thing. We haven’t passed the image name of the selected restaurant from the table view controller to the detail view controller. This is why the restaurantImageName variable is not assigned with any value.</p><h3>Passing Data Using Segues</h3><p>This comes to the core part of this chapter about data passing with segues. A segue manages the transition between view controllers, and contains the view controllers involved in the transition. When a segue is triggered, before the visual transition occurs, the storyboard runtime notifies the source view controller (i.e. RestaurantTableViewController) by calling the prepare(for:sender:) method:</p><pre>func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br><br>}</pre><p>The default implementation of the prepare(for:sender:) method does nothing. By overriding the method, you can pass any relevant data to the new controller, which is RestaurantDetailViewController in our project.</p><p>Segues can be triggered by multiple sources. As your storyboard becomes more complex, it is very likely that you’ll have more than one segue between view controllers. Therefore, the best practice is to give each segue a unique identifier. This identifier is a string to distinguish one segue from another. To assign an identifier for a segue, select the segue in the storyboard editor, and then go to the Attributes inspector. Set the value of the identifier to showRestaurantDetail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhZxVXaeWeBUQE200hGEhA.png" /><figcaption><em>Figure 13–13. Adding a segue identifier</em></figcaption></figure><p>You have to set both segue for datacell and favoritecell to the same identifier (i.e. showRestaurantDetail) because your app can switch between these two types of cells.</p><p>With the segue configured, insert the following code in the RestaurantTableViewControllerclass to override the default implementation of the prepare(for:sender:) method:</p><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>    if segue.identifier == &quot;showRestaurantDetail&quot; {<br>        if let indexPath = tableView.indexPathForSelectedRow {<br>            let destinationController = segue.destination as! RestaurantDetailViewController<br>            destinationController.restaurantImageName = self.restaurants[indexPath.row].image<br>        }<br>    }<br>}</pre><p>The first line of code is used to check the segue’s identifier. The block of code is only executed for the showRestaurantDetail segue. In the code block, we first retrieve the selected row by accessing tableView.indexPathForSelectedRow. The indexPath object should contain the selected cell.</p><p>A segue object contains both the source and destination view controllers involved in the transition. You use segue.destination to retrieve the destination controller. In this case, the destination controller is the RestaurantDetailViewController object. This is why we have to downcast it by using the as! operator. Lastly, we pass the image name of the selected restaurant to the destination controller.</p><p>Now, it’s ready to test the app. Hit the Run button to compile and run the app. This time, your app should work as expected. Select a restaurant in the table view, the detail view should display the image of the selected item.</p><h3>Disabling Large Titles</h3><p>Other than the home screen of the app, you may not want to use large titles to catch users’ attention. Apple provides developers an option to disable large titles in a particular view controller. For example, if you want to disable large titles in the detail view controller, you can insert the following line of code in the viewDidLoad() method of RestaurantDetailViewController:</p><pre>navigationItem.largeTitleDisplayMode = .never</pre><p>The code above changes the largeTitleDisplayMode of the navigation item to .never, indicating that it does not want to have the large title. The display mode can also be .always or .automatic. As the name suggests, .always means large title should always be used. If .automatic is set, it inherits the large title mode in the previous view controller.</p><h3>Your Exercise</h3><p>Wouldn’t it be better to show more restaurant information in the detail view? In this exercise, you’re required to add a few labels for displaying the name, type and location of the selected restaurant. Your resulting screen should look figure 13–14. If you understand how data passing works, it shouldn’t be difficult for you to make these changes. A hint is that instead of passing the name of the restaurant image, you need to pass the restaurant object to the detail view controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMvXhX3Mtorus0sSxP3iaA.png" /><figcaption><em>Figure 13–14. The detail view with more restaurant information</em></figcaption></figure><p>I highly recommend you to complete this exercise before moving onto the next chapter. Not only it helps you better understand the concept of segue and data passing, it will revise your knowledge of stack views and auto layout.</p><h3>Summary</h3><p>In this chapter, I have walked you through the basics of navigation controllers and segues. What we have built is really simple. We only pass the restaurant image from one view controller to another. But, by now you should know how to handle data passing between view controllers through segues.</p><p>For reference, you can download the complete Xcode project from</p><p><a href="https://drive.google.com/drive/folders/17UPH-_PHD-KpS0GrkUnt89mMNliU5BMU?usp=share_link">FoodPin-2 (1) - Google Drive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f3c27c47d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 - Table Row Deletion, Swipe for Actions, Activity Controller and MVC (UIKit)]]></title>
            <link>https://medium.com/@thanhtra.sqcb/9-table-row-deletion-swipe-for-actions-activity-controller-and-mvc-uikit-cb3225813b01?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb3225813b01</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 11:07:08 GMT</pubDate>
            <atom:updated>2023-03-02T11:07:08.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTfpPfjCAQwUJ1fPt51IkQ.png" /><figcaption>In the earlier chapter, you learned how to handle table row selection. But how about deletion? How can we delete a row from a table view? It’s a common question when building a table-based app. Select, delete, insert and update are the basic operations when dealing with data. We’ve discussed how to select a table row. Let’s talk about deletion in this chapter. In addition, we’ll go through a couple of new features to the FoodPin app:</figcaption></figure><ol><li>Adding a custom action button when a user swipes horizontally in a table row. This is usually known as <em>Swipe for More</em> action.</li><li>Adding a social sharing feature to the app, that enables users to easily share the restaurants.</li></ol><p>There is a lot to learn in this chapter, but it’s going to be fun and rewarding. Let’s get started.</p><h3>A Brief Introduction to Model View Controller</h3><p>We briefly mentioned the term MVC in the previous chapter when organizing the source files. Before jumping into the coding part, I would like to give you an introduction of Model-View-Controller (MVC) model, which is one of the most quoted design patterns for user interface programming.</p><p>I try to keep this book as practical as possible and seldom talk about the programming theories. Similar to OOP, if your ultimate goal is to become a professional developer, you can’t avoid learning Model-View-Controller. MVC is not a concept that applies to iOS programming only. You may have heard of it if you’ve studied other programming languages, such as Java or Ruby. It is a powerful design pattern used in designing software applications, whether it is a mobile app and a web app.</p><h3>Understanding Model-View-Controller</h3><blockquote><em>At the heart of MVC, and the idea that was the most influential to later frameworks, is what I call Separated Presentation. The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen. Domain objects should be completely self contained and work without reference to the presentation, they should also be able to support multiple presentations, possibly simultaneously. This approach was also an important part of the Unix culture, and continues today allowing many applications to be manipulated through both a graphical and command-line interface.</em></blockquote><blockquote><em>By Martin Fowler</em></blockquote><p>No matter which programming language you learn, one important concept that you need to know is <em>Separation of Concerns (SoC)</em>. The concept is pretty simple. Here, the <em>Concerns</em> are different aspects of software functionality. This concept encourages developers to break a complicated feature or program into several areas of concern such that each area has its own responsibility. The delegate pattern, that we explained in the earlier chapters, is one of the examples of SoC.</p><p>The <em>model-view-controller (MVC)</em> concept is another example of SoC. The core idea behind MVC is to separate a user interface into three areas (or groups of objects) that each area is responsible for a particular functionality. As the name suggests, MVC breaks a user interface into three parts:</p><ul><li><strong>Model</strong> — a model is responsible for holding the data or any operations on the data. The model can be as simple as an array object that stores the table data. Add, update and delete are examples of the operations. In the business world, these operations are usually known as business rules.</li><li><strong>View</strong> — a view manages the visual display of information. For example, UITableView displays data in a list format.</li><li><strong>Controller</strong> — a controller is a bridge between the model and the view. It translates the user interaction from the view (e.g. tap) into the appropriate action to be performed in the model. For example, a user taps the delete button in the view. Consequently, the controller triggers a delete operation in the model. Once finished, the model requests the view to refresh itself so as to reflect the update of the data model.</li></ul><p>To help you better understand MVC, let’s use the FoodPin app as an example. The app displays a list of restaurants in the table view. If you turn the implementation into a visual illustration, here is how the table data is displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntecSbOgHG4r4qX8TAot3w.png" /><figcaption><em>Figure 12–1. MVC Illustrated</em></figcaption></figure><p>The <em>Model</em> is the restaurants array which holds the list of restaurants. Each table row maps to an item of the restaurants array. The UITableView object is the actual <em>View</em> to be seen by a user. It&#39;s responsible for all the visuals (e.g. color of the table rows, style of the tableview, separator style, etc). The UITableViewController object, which is the <em>Controller</em>, acts as the bridge between the table view and the data model. It manages the table view and is responsible to load the data from the model.</p><h3>Deleting a Row from UITableView</h3><p>I hope you now have a better understanding of Model-View-Controller. Let’s move onto the coding part and see how we can delete a row from a table view. We’ll continue to develop the FoodPin app (if you haven’t completed the previous exercise, you can start with by downloading the project from</p><p><a href="https://drive.google.com/drive/folders/1DlQwLGamnu5jedMp5iF6-QHnl_eWNN-P?usp=share_link">FoodPin - Google Drive</a></p><p>and add the “delete” feature.</p><p>If you understand the MVC model, you probably have some ideas on the implementation of row deletion. There are three main tasks we have to do:</p><ol><li>Enable the swipe-to-delete feature of the table view so that the user can select the Delete option</li><li>Delete the corresponding table data from the data model</li><li>Update the snapshot and apply the change of table data</li></ol><h3>Enable the Swipe-to-delete feature</h3><p>In iOS apps, users normally swipe horizontally across a table row to reveal the Delete button. If you’ve read the documentation of the UITableViewDataSource protocol, you will find a method called tableView(_:commit:forRowAt:). This is the method that handles the deletion (or insertion) of a specific row.</p><p>The question is how can we implement the method? We are not using UITableViewDataSourcebut UITableViewDiffableDataSource to manage our data. If you dig deeper into <a href="https://developer.apple.com/documentation/uikit/uitableviewdiffabledatasource">the API documentation</a> of UITableViewDiffableDataSource, this protocol actually conforms to UITableViewDataSource! In this case, we can override tableView(_:commit:forRowAt:) and create the swipe-to-delete feature.</p><p>But wait! Referring to the configureDataSource() method, we are using the UITableViewDiffableDataSource class directly. How can we override the method and provide our own implementation?</p><p>Things get a little bit tricky here. In order to override the default implementation of the method, we have to subclass UITableViewDiffableDataSource and create our own version of diffable data source class.</p><p>Now go to the project navigator. Right click the <em>Model</em> folder and choose <em>New file….</em> Select the <em>Cocoa Touch Class</em> template and click <em>Next</em>. Name the class RestaurantDiffableDataSource and set its subclass to UITableViewDiffableDataSource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJzMbfYzIdJCoyBF4DBrhw.png" /><figcaption><em>Figure 12–2. Creating a new class</em></figcaption></figure><p>Once the file is created, update the content like this:</p><pre>import UIKit<br><br>enum Section {<br>    case all<br>}<br><br>class RestaurantDiffableDataSource: UITableViewDiffableDataSource&lt;Section, Restaurant&gt; {<br><br>    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -&gt; Bool {<br>        return true<br>    }<br><br>    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br><br>    }<br>}</pre><p>We created our custom version of diffable data source with the section type Section and the item type Restaurant. In the body, we override the tableView(_:commit:forRowAt:) method and the tableView(_:canEditRowAt:) method. The reason why we need to override the default implementation of tableView(_:canEditRowAt:) is that the cell is non-editable by default. This is why we override the method and return the value true to make the cells editable. The swipe-to-delete feature will not work if the cell is non-editable.</p><p>While we override the tableView(_:commit:forRowAt:) method, we haven&#39;t provided any implementation. This is good enough to enable the swipe-to-delete feature of a table view. If the method exists, the table view will automatically display a <em>Delete</em> button when the user swipes across a row.</p><p>Before we can test the app, there are a couple of changes we have to make. Since we have our custom version of UITableViewDiffableDataSource, switch over to RestaurantTableViewController.swift and change the UITableViewDiffableDataSource in the configureDataSource() method to RestaurantDiffableDataSource. The method should be like this after change:</p><pre>func configureDataSource() -&gt; RestaurantDiffableDataSource {<br><br>    let cellIdentifier = &quot;datacell&quot;<br><br>    let dataSource = RestaurantDiffableDataSource(<br>        tableView: tableView,<br>        cellProvider: {  tableView, indexPath, restaurant in<br>            let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell<br><br>            cell.nameLabel.text = restaurant.name<br>            cell.locationLabel.text = restaurant.location<br>            cell.typeLabel.text = restaurant.type<br>            cell.thumbnailImageView.image = UIImage(named: restaurant.image)<br>            cell.favoriteImageView.isHidden = restaurant.isFavorite ? false : true<br><br>            return cell<br>        }<br>    )<br><br>    return dataSource<br>}</pre><p>Please also note that I changed the value of cellIdentifier to datacell. You don&#39;t have to follow me. If you like, you can keep it to favoritecell.</p><p>There is one more change we have to make. Since we moved the Section enum to RestaurantDiffableDataSource.swift. We can delete the one declared in RestaurantTableViewController:</p><pre>enum Section {<br>    case all<br>}</pre><p>Now let’s have a quick test. Run the app on an iPhone simulator. Though the method is currently without any implementation, you should see the <em>Delete</em> button when swiping across a row. If the delete button is functional, you can either tap the <em>Delete</em> button or continue to swipe to the left edge to remove the item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZq8ovNv4nAu7hKMgnpuBA.png" /><figcaption><em>Figure 12–3. Swipe-to-delete feature</em></figcaption></figure><h3>Delete Row Data from the Table View Using Snapshot</h3><p>The next thing is to implement the method and write the code for removing the actual table data from the table view. From the method declaration, the indexPath parameter contains the row number of the cell, which is about to delete. You can make use of this information to retrieve the restaurant that we are going to delete.</p><p>Update the tableView(_:commit:forRowAt:) method of RestaurantDiffableDataSource like this:</p><pre>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br><br>    if editingStyle == .delete {<br>        if let restaurant = self.itemIdentifier(for: indexPath) {<br>            var snapshot = self.snapshot()<br>            snapshot.deleteItems([restaurant])<br>            self.apply(snapshot, animatingDifferences: true)<br>        }<br>    }<br>}</pre><p>The method supports two types of editing styles: <em>insert</em> and <em>delete</em>. Because we are only interested in the delete operation, we check the value of editingStyle before executing the code block. To find out the selected restaurant, we call the itemIdentifier method with the current indexPath.</p><p>The method returns us an optional, which means it can return a Restaurant object or nil. This is why we use the if let statement to perform a validation. Once we have the selected restaurant, we call the snapshot() method to get a copy of the data source’s current snapshot. Then we delete that restaurant by calling deleteItems. Lastly, we call apply with the updated snapshot to ask the table view to update its UI. Note that we also request the table view to animate the change by setting animatingDifferences to true.</p><p>Now run and test your app. Swipe any of the restaurants and delete the item. The table view should animate the deletion and remove the restaurant from the table.</p><p>If you’ve implemented the same “Delete” feature without diffable data sources, you should find that UITableViewDiffableDataSource make it very simple to keep the model data and view data in-sync. You no longer need to call reloadData to reload the table view or call deleteRows() to delete a specific table row. All you need is to grab a copy of the snapshot data, delete the item from the snapshot, and apply the changes to the table view.</p><h3>Swipe for More Actions Using UIContextualAction</h3><p>When you swipe left a table cell in the stock Mail app, you will see a Trash button, a Flag, and a More button. The More button will bring up an action sheet providing a list of options such as Reply, Flag, etc. If you swipe right, you will find the Archive button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJvpZjzwiYXyzU_m-mWl5Q.png" /><figcaption><em>Figure 12–4. Swipe for more in the Mail app</em></figcaption></figure><p>This <em>swipe-for-more</em> feature was first introduced in the stock iPhone apps in iOS 7. From iOS 8 to iOS 10, Apple made the “swipe-left” feature available to developers via a class named UITableViewRowAction. In iOS 11 (or up), Apple even lets developers implement the &quot;swipe-right&quot; feature in our own apps through new classes like UISwipeActionsConfiguration and UIContextualAction. You use the UIContextualAction class to create custom actions for table rows of any table view.</p><p>If we just need to implement the swipe to delete function in our app, the code that we implemented in the previous section is good enough. However, if we want to have a swipe-for-more feature, we need something more than that.</p><p>Before moving on, remove the whole method of tableView(_:commit:forRowAt:) in RestaurantDiffableDataSource:</p><pre>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br>    .<br>    .<br>    .<br>}</pre><p>We no longer need the method. Instead, we will implement something new to replace it. iOS provided two methods for handling swipe actions in table view cells:</p><ul><li>tableView(_:leadingSwipeActionsConfigurationForRowAt:)</li><li>tableView(_:trailingSwipeActionsConfigurationForRowAt:)</li></ul><p>Both methods are defined in UITableViewDelegate. The first method is designed for handling swipe-to-right actions, while the second one is for swipe-to-left actions.</p><p>Now let’s implement the second method in order to re-create the Delete function, plus adding a Share button. Insert the following method in RestaurantTableViewController:</p><pre>override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -&gt; UISwipeActionsConfiguration? {<br><br>    // Get the selected restaurant<br>    guard let restaurant = self.dataSource.itemIdentifier(for: indexPath) else {<br>        return UISwipeActionsConfiguration()<br>    }<br><br>    // Delete action<br>    let deleteAction = UIContextualAction(style: .destructive, title: &quot;Delete&quot;) { (action, sourceView, completionHandler) in<br><br>        var snapshot = self.dataSource.snapshot()<br>        snapshot.deleteItems([restaurant])<br>        self.dataSource.apply(snapshot, animatingDifferences: true)<br><br>        // Call completion handler to dismiss the action button<br>        completionHandler(true)<br>    }<br><br>    // Share action<br>    let shareAction = UIContextualAction(style: .normal, title: &quot;Share&quot;) { (action, sourceView, completionHandler) in<br>        let defaultText = &quot;Just checking in at &quot; + restaurant.name<br>        let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)<br><br>        self.present(activityController, animated: true, completion: nil)<br>        completionHandler(true)<br><br>    }<br><br>    // Configure both actions as swipe action<br>    let swipeConfiguration = UISwipeActionsConfiguration(actions: [deleteAction, shareAction])<br><br>    return swipeConfiguration<br>}</pre><p>The usage of UIContextualAction is very similar to that of UIAlertAction. You specify the title, the style and the block of code (i.e. the completion handler) to execute when a user taps the button. In this example, we have two contextual actions: one for <em>Delete</em> and another for <em>Share</em>.</p><p>The first line of code may be new to you. We use guard let instead of if let to check if we can get a valid restaurant. The guard statement works like this:</p><ul><li>If the returned value of itemIdentifier(for: indexPath) is not nil, save the Restaurantobject to the restaurant constant.</li><li>Otherwise, return an empty swipe action configuration.</li></ul><p>Can you use if let instead of guard let to perform the checking? Absolutely! However, the code looks cleaner when using guard let in this scenario.</p><p>To create the delete action, we instantiate a UIContextualAction object with the title &quot;Delete&quot; and .destructive style, indicating that the button should be in red. We also provide the code block to run after the delete action is selected. The code in the code block is similar to the one we wrote earlier, except that it has an additional line of code that calls completionHandler(true). After you successfully complete the action, you have to call the method to dismiss the action button. true indicates that the delete action has been performed.</p><p>Next, we create the share action using UIContextualAction with style .normal and title &quot;Share&quot;. If the style is set to .destructive, the button&#39;s background color will be set to gray by default. When a user taps the button, it brings up an activity controller for social sharing.</p><p>The UIActivityViewController class is a standard view controller that provides several standard services, such as copying items to the clipboard, sharing content on social media sites, sending items via Messages, etc. The class is very simple to use. Let&#39;s say you have a message for sharing. All you need to do is create an instance of UIActivityViewController with the message object, and then present the controller on the screen. That is what we have done in the above code snippet.</p><p>The last two lines of code is the most important part. It returns a UISwipeActionsConfigurationobject with an array of UIContextualAction objects (i.e. deleteAction and shareAction), telling the table view to create the swipe-for-more buttons.</p><p>Compile and run the app. Swipe across a table row and it’ll show you both Share and Delete buttons. Tapping the Share button will bring up a share menu like the one shown in figure 11–5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UCJrKAH4WSNTZ36shABiw.png" /><figcaption><em>Figure 12–5. Swipe to Share button on the simulator</em></figcaption></figure><p>In the simulator, you can only find a few options such as copying items to the pasteboard and save to files. If the app is run on a real device, the share menu will offer more applications. Apple allows developers to define custom services that appear in the share menu. The available items vary from device to device, depending on the apps installed.</p><p>The UIActivityViewController class does not limit you from sharing content in text format. If you pass it a UIImage object during initialization, your app will allow users to copy images or share them to other applications. Modify the shareAction constant to the following:</p><pre>let shareAction = UIContextualAction(style: .normal, title: &quot;Share&quot;) { (action, sourceView, completionHandler) in<br>    let defaultText = &quot;Just checking in at &quot; + restaurant.name<br><br>    let activityController: UIActivityViewController<br><br>    if let imageToShare = UIImage(named: restaurant.image) {<br>        activityController = UIActivityViewController(activityItems: [defaultText, imageToShare], applicationActivities: nil)<br>    } else  {<br>        activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)<br>    }<br><br>    self.present(activityController, animated: true, completion: nil)<br>    completionHandler(true)<br>}</pre><p>In the code above, we added an imageToShare object for image sharing. When loading an image, it is possible that the image is failed to load. This is why the UIImage class returns an optional during initialization. Again, we use if let to verify if an optional contains a value or not. If the image can be loaded properly, we pass both defaultText and imageToShare to UIActivityViewController during initialization.</p><pre>activityController = UIActivityViewController(activityItems: [defaultText, imageToShare], applicationActivities: nil)</pre><p>UIActivityViewController will automatically embed the image of the selected restaurant when the user chooses to copy the content to the pasteboard. You can try it out by selecting <em>Copy</em> and then paste it into the built-in Messages app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyUKvbxu5zqcyxO3P8YpuQ.png" /><figcaption><em>Figure 12–6. Copy the selected restaurant and paste it into the Messages app</em></figcaption></figure><h3>Understanding SF Symbols</h3><blockquote><em>With over 4,000 symbols, SF Symbols is a library of iconography designed to integrate seamlessly with San Francisco, the system font for Apple platforms. Symbols come in nine weights and three scales, and automatically align with text labels. They can be exported and edited using vector graphics editing tools to create custom symbols with shared design characteristics and accessibility features. SF Symbols 4 features over 700 new symbols, variable color, automatic rendering, and new unified layer annotation.</em></blockquote><p>Before I showed you how to customize the contextual action with icons, let’s first talk about where the icons come from. Needless to say, you can provide your own images to use in the app. In iOS 13, Apple introduced a large set of system images called SF Symbols that allows developers to use them in any apps. Along with the release of Xcode 14, Apple released SF Symbols 4 with more configurable symbols, multicolor support, and enhanced color customizations.</p><p>These images are referred as symbols since it’s integrated with the built-in San Francisco font. To use these symbols, no extra installation is required. As long as your app is deployed to a device running iOS 13 (or later), you can access these symbols directly.</p><p>To use the symbols, all you need to prepare is find out the name of the symbol. With over 4,000 symbols available for your use, Apple has released an app called <a href="https://devimages-cdn.apple.com/design/resources/download/SF-Symbols-4.dmg">SF Symbols 4</a>(<a href="https://devimages-cdn.apple.com/design/resources/download/SF-Symbols-4.dmg">https://devimages-cdn.apple.com/design/resources/download/SF-Symbols-4.dmg</a>), so that you can easily explore the symbols and locate the one that fits your need. I highly recommend you to install the app before proceeding to the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFLNB9WkwU1WxxaM6cCHRQ.png" /><figcaption><em>Figure 12–7. SF Symbols App</em></figcaption></figure><h3>Customizing UIContextualAction</h3><p>Okay, let’s see how to customize the action buttons. By default, the action buttons are either in red or gray. The UIContextualAction class provides a couple of the properties for developers to customize its style including background color and icon. The code looks like this:</p><pre>shareAction.backgroundColor = UIColor.systemOrange<br>shareAction.image = UIImage(systemName: &quot;square.and.arrow.up&quot;)</pre><p>You set the backgroundColor property to change its background color and the image property to add an icon. To use the built-in images provided by SF Symbols, you need to instantiate an UIImage and provide the image name in the systemName parameter.</p><p>This is the first time we work with color programmatically. The UIKit framework provides a UIColor class to represent color. Many methods in UIKit require you to provide color using a UIColor object. iOS offers a wide range of system colors that you can use directly.</p><p>Alternatively, if you want to use your own color, you can create a UIColor object using RGB component values. The component values should be within 0 and 1. If you&#39;re a web designer or have some experience with graphics design, you know that the RGB values are on a scale of 0 to 255. To conform with the requirement of UIColor, you have to divide each of the component values by 255 when creating a UIColor object. Here is an example:</p><pre>shareAction.backgroundColor = UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 38.0/255.0, alpha: 1.0)</pre><p>Apple encourages us to use the built-in system color because it supports both light and dark modes. And, the colors automatically adapt to vibrancy and changes in accessibility settings like Increase Contrast and Reduce Transparency. Therefore, we will use the system color in our code change. You can refer to this link (<a href="https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/">https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/</a>) to check out all the supported system colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg-m0M2wGaa6u5_ebF9W9g.png" /><figcaption><em>Figure 12–8. Some system colors for both light and dark mode</em></figcaption></figure><p>Now, insert the following lines of code in the tableView(_:trailingSwipeActionsConfigurationForRowAt:) method and place it before the instantiation of swipeConfiguration:</p><pre>deleteAction.backgroundColor = UIColor.systemRed<br>deleteAction.image = UIImage(systemName: &quot;trash&quot;)<br>shareAction.backgroundColor = UIColor.systemOrange<br>shareAction.image = UIImage(systemName: &quot;square.and.arrow.up&quot;)</pre><p>After you made the changes, test the app again and see if you like the new color. Otherwise, modify the system color and change to your preferred one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*-CDim5FGTisJ71pMVASbGg.png" /><figcaption><em>Figure 12–9. Customizing the action buttons with new background color and icons</em></figcaption></figure><pre>Quick tip: Like me, if you are not a designer, you may need some color inspiration. You can check out Adobe Color CC (color.adobe.com) and Flat UI Color Picker (flatuicolorpicker.com). You&#39;ll find a lot of color combinations for designing your app.</pre><h3>Testing on iPad</h3><p>Did you try to run the app on iPad? The app crashes when you tap the <em>Share</em> button and the following error shows up in console:</p><pre>*** Terminating app due to uncaught exception &#39;NSGenericException&#39;, reason: &#39;UIPopoverPresentationController (&lt;UIPopoverPresentationController: 0x7fadaa51f7e0&gt;) should have a non-nil sourceView or barButtonItem set before the presentation occurs.&#39;<br>terminating with uncaught exception of type NSException<br>CoreSimulator 732.17 - Device: iPad Pro (11-inch) (2nd generation) (02AA483A-0CAA-4645-8B8F-90D3397769A3) - Runtime: iOS 14.1 (18A8394) - DeviceType: iPad Pro (11-inch) (2nd generation)</pre><blockquote><em>When presenting the view controller, you must do so using the appropriate means for the current device. On iPad, you must present the view controller in a popover. On iPhone and iPod touch, you must present it modally.</em></blockquote><blockquote><a href="https://developer.apple.com/documentation/uikit/uiactivityviewcontroller"><em>https://developer.apple.com/documentation/uikit/uiactivityviewcontroller</em></a></blockquote><p>Similar to what we have discussed in the previous chapter, UIActivityViewController will be presented in the popover style on large devices. I believe you know how to fix the bug.</p><blockquote><em>You must provide location information for this popover through the view controller’s popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem.</em></blockquote><p>When presenting the activity view controller using the popover style, you have to configure the source view of its popoverPresentationController. The source view indicates the view containing the anchor rectangle for the popover. You will understand what it means after implementing the popover.</p><p>Now, insert the following code before calling the self.present(activityController, animated: true, completion: nil) method in shareAction:</p><pre>if let popoverController = activityController.popoverPresentationController {<br>    if let cell = tableView.cellForRow(at: indexPath) {<br>        popoverController.sourceView = cell<br>        popoverController.sourceRect = cell.bounds<br>    }<br>}</pre><p>Test the app on the iPad simulator again. It should work now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyNdHu_Bfy73D9nsZOI-zQ.png" /><figcaption><em>Figure 12–10. The share action shows a popover on iPad</em></figcaption></figure><h3>Exercise</h3><p>Up till now, we only implement the swipe left action. How about swipe right? I will leave you to implement the feature as an exercise. As mentioned before, all you need is to provide the implementation of the following method:</p><pre>override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -&gt; UISwipeActionsConfiguration? {<br><br>}</pre><p>What I need you to do is add a check-in action when the user swipes right the cell. In the SF Symbols app, you should find the images named heart.fill and heart.slash.fill. You can use these images for the &quot;Mark as favorite&quot; action. After you finish the exercise, your app should allow users to swipe right to perform the &quot;Mark as favorite&quot; action that we covered before. When you swipe right on a cell with the heart icon, the tick icon will be replaced by the undo icon. Figure 12-11 illustrates the swipe-to-favorite action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoRYipE1FhgqSnX-1as4Vw.png" /><figcaption><em>Figure 12–11. How the Swipe-to-favorite button works</em></figcaption></figure><h3>Summary</h3><p>In this chapter, I gave you a brief overview of MVC, showed you how to manage deletion in a table view, and taught you how to create swipe action in table view cells using UIContextualAction. You also learned how to use UIActivityViewController for implementing a sharing feature. The FoodPin app is getting better and better. You should be proud of your achievement so far.</p><p>The MVC concept is important. If you’re a programming newbie, it may take you some time to fully understand the material. Feeling confused? Just take a break and grab yourself a coffee. After your break, go over the chapter again. Probably you’ll find it easier to digest.</p><p>For reference, you can download the complete Xcode project (including the solution to the exercise) from</p><p><a href="https://drive.google.com/drive/folders/1EduRjf6XibE_FE_MD1CcMvmEY6rR-c-M?usp=share_link">FoodPin (1) - Google Drive</a></p><p>In the next chapter, we’ll take a look at something new and create a navigation controller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb3225813b01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 - Object Oriented Programming, Project Organization and Code Documentation (UIKit)]]></title>
            <link>https://medium.com/@thanhtra.sqcb/8-object-oriented-programming-project-organization-and-code-documentation-uikit-7f5bf8410f02?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f5bf8410f02</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 10:54:28 GMT</pubDate>
            <atom:updated>2023-03-02T10:54:37.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lfD3sRRVN7urAutfPjAag.png" /></figure><p>If you read from the very beginning of the book and have worked through all the projects, you’ve gone pretty far. By now, you should be able to build a table-based iOS app, which works on both iPhone and iPad, using Interface Builder. We’ll further enhance the FoodPin app and add more features. However, we will dive deeper into iOS app development and learn other APIs. I want to introduce you the basics of Object Oriented Programming and teach you how to write better code.</p><p>Don’t be scared by the term “Object Oriented Programming” or OOP in short. It’s not a new kind of programming language, but a programming concept. While some programming books start out by introducing the OOP concept, I intentionally left it out when I began writing this book. I want to keep things interesting and show you how to create an app. I don’t want to scare you away from building apps, just because of a technical term or concept. Having said that, I think it’s time to discuss OOP. After going through 10 chapters and you’re still reading the book, I believe you’re determined to learn iOS programming. And, I believe you really want to take your programming skills to the next level to become a professional developer.</p><p>Okay, let’s get started.</p><h3>The Basic Theory of Object Oriented Programming</h3><p>Like Objective-C, Swift is known as an Object Oriented Programming (OOP) language. OOP is a way of constructing software application composed of objects. In other words, the code written in an app in some ways deals with objects of some kinds. The UIViewController, UIButton, UINavigationController, and UITableView objects that you have used are some sample objects that come with the iOS SDK. Not only can you use the built-in objects, you have already created your own objects in the project, such as RestaurantTableViewController and RestaurantTableViewCell.</p><p>First, why OOP? One important reason is that we want to decompose complex software into smaller pieces (or building block) which are easier to develop and manage. Here, the smaller pieces are the objects. Each object has its own responsibility and objects coordinate with each other in order to make the software work. That is the basic concept of OOP. Take the Hello World app, that we’ve built at the very beginning, as an example. The UIViewController object is responsible for controlling the view of the app and its view object is used for holding the Hello World button. The UIButton (i.e. Hello World button) object implements a standard iOS button on the touch screen and listens to any touch events. On the other hand, the UIAlertControllerobject displays an alert message to a user. After all, these objects work together to create the Hello World app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggIyRRCljs5RrfNMvQ0JXw.png" /><figcaption><em>Figure 11–1. Sample Objects in Hello World App</em></figcaption></figure><p>In Object Oriented Programming, an object shares two characteristics: <em>properties</em> and <em>functionalities</em>. Let’s consider a real world object — <em>Car</em>. A car has its own color, model, top speed, manufacturer, etc. These are the properties of a car. In terms of functionalities, a car should provide basic functions, such as accelerate, brake, steering, etc.</p><p>Software objects are conceptually similar to real-world objects. If we go back to the iOS world, let’s take a look at the properties and functionalities of the UIButton object in the Hello World app:</p><ul><li><strong>Properties</strong> — Background, size, color, and font are examples of the UIButton&#39;s properties</li><li><strong>Functionalities</strong> — When the button is tapped, it recognizes the tap event. The ability to detect a touch is one of the many functions of UIButton.</li></ul><p>In earlier chapters, you always come across the term <em>method</em>. In Swift, we create methods to provide the functionalities of an object. Usually, a method corresponds to a particular function of an object.</p><pre>Note: You may wonder what is the difference between functions and methods? In fact, they are functionally the same. Functions defined in a class are known as methods.</pre><h3>Classes, Objects and Instances</h3><p>Other than methods and objects, you have come across terms like <em>instance</em> and <em>class</em> . All these are the common terms in OOP. Let me give you a brief explanation.</p><p>A class is a blueprint or prototype from which objects are created. Basically, a class consists of properties and methods. Let’s say, we want to define a Course class. A Course class contains properties, such as <em>name</em>, <em>course code</em>, and the <em>total number of students</em>.</p><p>This class represents the blueprint of a course. We can use it to create different courses like iOS Programming course with course code <em>IPC101</em>, Cooking course with course code <em>CC101</em>, etc. Here, the “iOS Programming course” and “Cooking course” are known as the <em>objects</em> of the Courseclass. We typically refer a single course as an <em>instance</em> of the Course class. For the sake of simplicity, the term <em>instance</em> and <em>object</em> are sometimes interchangeable.</p><blockquote><em>A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.</em></blockquote><blockquote><em>Source: </em><a href="http://stackoverflow.com/questions/3323330/difference-between-object-and-instance"><em>http://stackoverflow.com/questions/3323330/difference-between-object-and-instance</em></a></blockquote><h3>Structures</h3><blockquote>Structures<em> and </em>classes<em> are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.</em></blockquote><blockquote><em>- Apple Documentation (</em><a href="https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html"><em>https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html</em></a><em>)</em></blockquote><p>Other than classes, you can use use structures (or structs) in Swift to create your own type with properties and methods. <em>Structs</em> in Swift are very similar to <em>Classes</em> and have a lot in common. Both can define properties to store values and methods to provide functionalities. Both can create their own initializers to configure the initial state of the object.</p><p>Inheritance is one of the important features of Object Oriented Programming. Recalled that we have created the RestaurantTableViewController class, which is a subclass of the UITableViewController, this is a sample usage of class inheritance. The RestaurantTableViewController class inherits all the properties and methods of UITableViewController. Whenever we need to provide specialization for a particular function, we override the original function of the super class.</p><p>Structs, however, do not allow inheritance. You can’t inherit one struct from another. This is one of main differences between Classes and Structs in Swift.</p><p>Types in Swift fall into two categories: <em>value types</em> and <em>reference types</em>. All structures in Swift are value types, while classes are reference types. This is another core difference between Classes and Structs. For structs, each instance has a unique copy of its data. On the other hand, reference types (classes) share a single copy of the data. When you assign an instance of a class to another variable, rather than copy the data of that instance, a reference to that instance is used.</p><p>Let me demonstrate the difference between value types (struct) and reference types (class) using an example. In the code snippet below, we have a class named Car with a property named brand. We create an instance of Car and assign it to a car1 variable. Then we assign car1 to another variable named car2. Lastly, we modify the brand value of car1.</p><pre>class Car {<br>    var brand = &quot;Tesla&quot;<br>}<br><br>var car1 = Car()<br>var car2 = car1<br><br>car1.brand = &quot;Audi&quot;<br>print(car2.brand)</pre><p>Can you guess the brand value of car2? Should it be Tesla or Audi? The answer is <em>Audi</em>. This is the nature of reference types. Both car1 and car2 are referring to the same instance, sharing the same copy of the data.</p><p>Contrarily, if you rewrite the same piece of code with struct (i.e. value types), you will see a different result.</p><pre>struct Car {<br>    var brand = &quot;Tesla&quot;<br>}<br><br>var car1 = Car()<br>var car2 = car1<br><br>car1.brand = &quot;Audi&quot;<br>print(car2.brand)</pre><p>In this case, only the brand value of car1 is updated to Audi. For car2, its brand is still Tesla because each variable of value types has its own copy of data. Figure 11-2 illustrates the difference between classes and structs visually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrRynZyzRcYilT4ahEFj_Q.png" /><figcaption><em>Figure 11–2. Illustrates the difference between value types and reference types</em></figcaption></figure><p>Since both classes and strutures provides similar features, which one should you use? In general, use structures to create your own type by default. This is a recommendation from Apple (<a href="https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes">https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes</a>). In case if you need additional functionalities like inheritance, choose classes over structs.</p><h3>Revisit the FoodPin Project</h3><p>So, why do we cover OOP in this chapter? There is no better way to explain the concept than showing you an example. Take a look at the FoodPin project again.</p><p><a href="https://drive.google.com/drive/folders/1f3iFy3CnxRmi4OwN_2jDtRaaDUYLtr9b?usp=share_link">FoodPin-3 - Google Drive</a></p><p>In the RestaurantTableViewController class, we created multiple arrays to store the names, types, locations, and images of the restaurants.</p><pre>var restaurantNames = [&quot;Cafe Deadend&quot;, &quot;Homei&quot;, &quot;Teakha&quot;, &quot;Cafe Loisl&quot;, &quot;Petite Oyster&quot;, &quot;For Kee Restaurant&quot;, &quot;Po&#39;s Atelier&quot;, &quot;Bourke Street Bakery&quot;, &quot;Haigh&#39;s Chocolate&quot;, &quot;Palomino Espresso&quot;, &quot;Upstate&quot;, &quot;Traif&quot;, &quot;Graham Avenue Meats&quot;, &quot;Waffle &amp; Wolf&quot;, &quot;Five Leaves&quot;, &quot;Cafe Lore&quot;, &quot;Confessional&quot;, &quot;Barrafina&quot;, &quot;Donostia&quot;, &quot;Royal Oak&quot;, &quot;CASK Pub and Kitchen&quot;]<br><br>var restaurantImages = [&quot;cafedeadend&quot;, &quot;homei&quot;, &quot;teakha&quot;, &quot;cafeloisl&quot;, &quot;petiteoyster&quot;, &quot;forkeerestaurant&quot;, &quot;posatelier&quot;, &quot;bourkestreetbakery&quot;, &quot;haighschocolate&quot;, &quot;palominoespresso&quot;, &quot;upstate&quot;, &quot;traif&quot;, &quot;grahamavenuemeats&quot;, &quot;wafflewolf&quot;, &quot;fiveleaves&quot;, &quot;cafelore&quot;, &quot;confessional&quot;, &quot;barrafina&quot;, &quot;donostia&quot;, &quot;royaloak&quot;, &quot;caskpubkitchen&quot;]<br><br>var restaurantLocations = [&quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Sydney&quot;, &quot;Sydney&quot;, &quot;Sydney&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;London&quot;, &quot;London&quot;, &quot;London&quot;, &quot;London&quot;]<br><br>var restaurantTypes = [&quot;Coffee &amp; Tea Shop&quot;, &quot;Cafe&quot;, &quot;Tea House&quot;, &quot;Austrian / Causual Drink&quot;, &quot;French&quot;, &quot;Bakery&quot;, &quot;Bakery&quot;, &quot;Chocolate&quot;, &quot;Cafe&quot;, &quot;American / Seafood&quot;, &quot;American&quot;, &quot;American&quot;, &quot;Breakfast &amp; Brunch&quot;, &quot;Coffee &amp; Tea&quot;, &quot;Coffee &amp; Tea&quot;, &quot;Latin American&quot;, &quot;Spanish&quot;, &quot;Spanish&quot;, &quot;Spanish&quot;, &quot;British&quot;, &quot;Thai&quot;]<br><br>var restaurantIsFavorites = Array(repeating: false, count: 21)</pre><p>All these data are actually related to a list of restaurants. Why do we need to separate them into multiple arrays? Have you ever wondered if we can group these data together?</p><p>In Object Oriented Programming, these data can be characterized as the properties of a restaurant. Instead of storing these data in separate arrays, we can create a Restaurantstructure to model a restaurant and store multiple restaurants in an array of Restaurantobjects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEv74EXyaDaIVXlexD1zqQ.png" /></figure><p>Now let’s tweak the FoodPin project, create the Restaurant struct and convert the code to use a list of Restaurant objects.</p><h3>Creating a Restaurant Struct</h3><p>First, we’ll start with the Restaurant struct. In the project navigator, right click on the FoodPinfolder and select &quot;New File…&quot;. This time we are not extending the UI objects provided by the iOS SDK. Instead, we are going to create a brand new struct. So, choose the &quot;Swift File&quot; template under Source and click &quot;Next&quot;. Name the file Restaurant.swift and save it in the project folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nr9orMN7vs_MBtxHiuz0HQ.png" /><figcaption><em>Figure 11–4. Creating a new class using the Swift File template</em></figcaption></figure><p>Once completed, declare the Restaurant struct in the Restaurant.swift file using the below code:</p><pre>struct Restaurant {<br>    var name: String<br>    var type: String<br>    var location: String<br>    var image: String<br>    var isFavorite: Bool<br><br>    init(name: String, type: String, location: String, image: String, isFavorite: Bool) {<br>        self.name = name<br>        self.type = type<br>        self.location = location<br>        self.image = image<br>        self.isFavorite = isFavorite<br>    }<br><br>    init() {<br>        self.init(name: &quot;&quot;, type: &quot;&quot;, location: &quot;&quot;, image: &quot;&quot;, isFavorite: false)<br>    }<br>}</pre><p>You use the struct keyword to define a structure. The code above defines a Restaurant struct with five properties including name, type, location, image and isFavorite. Except for isFavorite, which is a boolean (i.e. Bool), the rest of the properties are of the type String. You can either set a default value or explicitly specify the type for each property. Here we demonstrate the latter option.</p><h4>Initializers Explained</h4><p>Initialization is the process of preparing an instance of a structure (or class). When you create an object, the initializer is called for setting an initial value for each stored property on that instance and performing any extra setup, before the instance is ready to use. You use the initkeyword to define an initializer. In its simplest form, it looks like this:</p><pre>init() {<br><br>}</pre><p>You can also customize an initializer to take input parameters, just like the one we have defined in the Restaurant struct. Our initializer has five parameters. Each of them is given a name and explicitly specified with a type. In the initializer, it initializes the values of the property with the given values.</p><p>To create an instance of the Restaurant struct, the syntax is like this:</p><pre>Restaurant(name: &quot;Thai Cafe&quot;, type: &quot;Thai&quot;, location: &quot;London&quot;, image: &quot;thaicafe&quot;, isFavorite: false)</pre><p>You are allowed to define multiple initializers that accepts different parameters. In the code, we created another initializer for convenience purpose.</p><pre>init() {<br>    self.init(name: &quot;&quot;, type: &quot;&quot;, location: &quot;&quot;, image: &quot;&quot;, isFavorite: false)<br>}</pre><p>Without this initializer, you can initialize an empty Restaurant object like this:</p><pre>Restaurant(name: &quot;&quot;, type: &quot;&quot;, location: &quot;&quot;, image: &quot;&quot;, isFavorite: false)</pre><p>Now with the convenience initializer, you can initialize the same object like this:</p><pre>Restaurant()</pre><p>It saves you time from typing all the initialization parameters every time you need to initialize an empty Restaurant object.</p><h4>The self Keyword</h4><p>What’s the self keyword in the initializer? In Swift, you use self to differentiate between property names and arguments in initializers. Because the arguments have the same name as the properties, we use self to refer to the property of the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihT6VFlKBjE4kVDDKQonsw.png" /><figcaption><em>Figure 11–5. The use of self keyword</em></figcaption></figure><h4>Default Initializers</h4><p>You can actually assign each property with a default value and omit the initializator. Swift will generate the default initalizer behind the scene. Therefore, a short version of the Restaurantstruct can be written like this:</p><pre>struct Restaurant {<br>    var name: String = &quot;&quot;<br>    var type: String = &quot;&quot;<br>    var location: String = &quot;&quot;<br>    var image: String = &quot;&quot;<br>    var isFavorite: Bool = false<br>}</pre><h3>Using the Array of Restaurant Objects</h3><p>With a basic understanding of classes, structs, and object initializations, let’s go back to the FoodPin project and combine the existing arrays into an array of Restaurant objects. First, delete the restaurant-related arrays from the RestaurantTableViewController class:</p><pre>var restaurantNames = [&quot;Cafe Deadend&quot;, &quot;Homei&quot;, &quot;Teakha&quot;, &quot;Cafe Loisl&quot;, &quot;Petite Oyster&quot;, &quot;For Kee Restaurant&quot;, &quot;Po&#39;s Atelier&quot;, &quot;Bourke Street Bakery&quot;, &quot;Haigh&#39;s Chocolate&quot;, &quot;Palomino Espresso&quot;, &quot;Upstate&quot;, &quot;Traif&quot;, &quot;Graham Avenue Meats&quot;, &quot;Waffle &amp; Wolf&quot;, &quot;Five Leaves&quot;, &quot;Cafe Lore&quot;, &quot;Confessional&quot;, &quot;Barrafina&quot;, &quot;Donostia&quot;, &quot;Royal Oak&quot;, &quot;CASK Pub and Kitchen&quot;]<br><br>var restaurantImages = [&quot;cafedeadend&quot;, &quot;homei&quot;, &quot;teakha&quot;, &quot;cafeloisl&quot;, &quot;petiteoyster&quot;, &quot;forkee&quot;, &quot;posatelier&quot;, &quot;bourkestreetbakery&quot;, &quot;haigh&quot;, &quot;palomino&quot;, &quot;upstate&quot;, &quot;traif&quot;, &quot;graham&quot;, &quot;waffleandwolf&quot;, &quot;fiveleaves&quot;, &quot;cafelore&quot;, &quot;confessional&quot;, &quot;barrafina&quot;, &quot;donostia&quot;, &quot;royaloak&quot;, &quot;cask&quot;]<br><br>var restaurantLocations = [&quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Sydney&quot;, &quot;Sydney&quot;, &quot;Sydney&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;London&quot;, &quot;London&quot;, &quot;London&quot;, &quot;London&quot;]<br><br>var restaurantTypes = [&quot;Coffee &amp; Tea Shop&quot;, &quot;Cafe&quot;, &quot;Tea House&quot;, &quot;Austrian / Causual Drink&quot;, &quot;French&quot;, &quot;Bakery&quot;, &quot;Bakery&quot;, &quot;Chocolate&quot;, &quot;Cafe&quot;, &quot;American / Seafood&quot;, &quot;American&quot;, &quot;American&quot;, &quot;Breakfast &amp; Brunch&quot;, &quot;Coffee &amp; Tea&quot;, &quot;Coffee &amp; Tea&quot;, &quot;Latin American&quot;, &quot;Spanish&quot;, &quot;Spanish&quot;, &quot;Spanish&quot;, &quot;British&quot;, &quot;Thai&quot;]<br><br>var restaurantIsFavorites = Array(repeating: false, count: 21)</pre><p>Instead of using the above arrays, replace them with a new array of Restaurant objects:</p><pre>var restaurants:[Restaurant] = [<br>    Restaurant(name: &quot;Cafe Deadend&quot;, type: &quot;Coffee &amp; Tea Shop&quot;, location: &quot;Hong Kong&quot;, image: &quot;cafedeadend&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Homei&quot;, type: &quot;Cafe&quot;, location: &quot;Hong Kong&quot;, image: &quot;homei&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Teakha&quot;, type: &quot;Tea House&quot;, location: &quot;Hong Kong&quot;, image: &quot;teakha&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Cafe loisl&quot;, type: &quot;Austrian / Causual Drink&quot;, location: &quot;Hong Kong&quot;, image: &quot;cafeloisl&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Petite Oyster&quot;, type: &quot;French&quot;, location: &quot;Hong Kong&quot;, image: &quot;petiteoyster&quot;, isFavorite: false),<br>    Restaurant(name: &quot;For Kee Restaurant&quot;, type: &quot;Bakery&quot;, location: &quot;Hong Kong&quot;, image: &quot;forkee&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Po&#39;s Atelier&quot;, type: &quot;Bakery&quot;, location: &quot;Hong Kong&quot;, image: &quot;posatelier&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Bourke Street Backery&quot;, type: &quot;Chocolate&quot;, location: &quot;Sydney&quot;, image: &quot;bourkestreetbakery&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Haigh&#39;s Chocolate&quot;, type: &quot;Cafe&quot;, location: &quot;Sydney&quot;, image: &quot;haigh&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Palomino Espresso&quot;, type: &quot;American / Seafood&quot;, location: &quot;Sydney&quot;, image: &quot;palomino&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Upstate&quot;, type: &quot;American&quot;, location: &quot;New York&quot;, image: &quot;upstate&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Traif&quot;, type: &quot;American&quot;, location: &quot;New York&quot;, image: &quot;traif&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Graham Avenue Meats&quot;, type: &quot;Breakfast &amp; Brunch&quot;, location: &quot;New York&quot;, image: &quot;graham&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Waffle &amp; Wolf&quot;, type: &quot;Coffee &amp; Tea&quot;, location: &quot;New York&quot;, image: &quot;waffleandwolf&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Five Leaves&quot;, type: &quot;Coffee &amp; Tea&quot;, location: &quot;New York&quot;, image: &quot;fiveleaves&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Cafe Lore&quot;, type: &quot;Latin American&quot;, location: &quot;New York&quot;, image: &quot;cafelore&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Confessional&quot;, type: &quot;Spanish&quot;, location: &quot;New York&quot;, image: &quot;confessional&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Barrafina&quot;, type: &quot;Spanish&quot;, location: &quot;London&quot;, image: &quot;barrafina&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Donostia&quot;, type: &quot;Spanish&quot;, location: &quot;London&quot;, image: &quot;donostia&quot;, isFavorite: false),<br>    Restaurant(name: &quot;Royal Oak&quot;, type: &quot;British&quot;, location: &quot;London&quot;, image: &quot;royaloak&quot;, isFavorite: false),<br>    Restaurant(name: &quot;CASK Pub and Kitchen&quot;, type: &quot;Thai&quot;, location: &quot;London&quot;, image: &quot;cask&quot;, isFavorite: false)<br>]</pre><p>Once you replaced the original arrays with the restaurants array, you&#39;ll end up with a few errors in Xcode because some of the code still refer to the old arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLB9NdsSkElG5bJqn1jdfw.png" /><figcaption><em>Figure 11–6. You can click the cross indicator to reveal the errors</em></figcaption></figure><p>To fix the errors, we have to modify the code to use the new restaurants array. First, update the configureDataSource() method like this:</p><pre>func configureDataSource() -&gt; UITableViewDiffableDataSource&lt;Section, Restaurant&gt; {<br><br>    let cellIdentifier = &quot;datacell&quot;<br><br>    let dataSource = UITableViewDiffableDataSource&lt;Section, Restaurant&gt;(<br>        tableView: tableView,<br>        cellProvider: {  tableView, indexPath, restaurant in<br>            let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell<br><br>            cell.nameLabel.text = restaurant.name<br>            cell.locationLabel.text = restaurant.location<br>            cell.typeLabel.text = restaurant.type<br>            cell.thumbnailImageView.image = UIImage(named: restaurant.image)<br>            cell.favoriteImageView.isHidden = restaurant.isFavorite ? false : true<br><br>            return cell<br>        }<br>    )<br><br>    return dataSource<br>}</pre><p>Since we now use an array of Restaurant object instead of an array of restaurant names to model the restaurants, the item type of UITableViewDiffableDataSource is now changed to Restaurant. For the cellProvider closure, it now passes us a Restaurant object instead of a String. So, we can retrieve the restaurant data by accessing the properties of the Restaurantobject.</p><p>Next, replace these lines of code in viewDidLoad():</p><pre>var snapshot = NSDiffableDataSourceSnapshot&lt;Section, String&gt;()<br>snapshot.appendSections([.all])<br>snapshot.appendItems(restaurantNames, toSection: .all)</pre><p>With:</p><pre>var snapshot = NSDiffableDataSourceSnapshot&lt;Section, Restaurant&gt;()<br>snapshot.appendSections([.all])<br>snapshot.appendItems(restaurants, toSection: .all)</pre><p>Again, the item type of the diffable data source is now changed from String to Restaurant. Instead of appending the restaurantNames to the section, we add the items in the restaurantsarray.</p><p>Other than that, you should see a number of errors in the tableView(_:didSelectRowAt:)method since the restaurantIsFavorites array is no longer available. You can replace the code of favoriteActionTitle and favoriteAction like below:</p><pre>let favoriteActionTitle = self.restaurants[indexPath.row].isFavorite ? &quot;Remove from favorites&quot; : &quot;Mark as favorite&quot;<br>let favoriteAction = UIAlertAction(title: favoriteActionTitle, style: .default, handler: {<br>    (action:UIAlertAction!) -&gt; Void in<br><br>    let cell = tableView.cellForRow(at: indexPath) as! RestaurantTableViewCell<br><br>    cell.favoriteImageView.isHidden = self.restaurants[indexPath.row].isFavorite<br><br>    self.restaurants[indexPath.row].isFavorite = self.restaurants[indexPath.row].isFavorite ? false : true<br><br>})</pre><p>We now access the isFavorite property of the selected restaurant objects to check its value.</p><p>Do we fix all the errors? Not yet. If you scroll back to the configureDataSource() method and the viewDidLoad() method, you should see a bunch of errors, complaining the type Restaurant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bur0Ztkxf6Qh9WfIZ6vRpA.png" /><figcaption><em>Figure 11–7. Error message for the Restaurant type</em></figcaption></figure><p>What’s the problem of the Restaurant struct? What does the error message mean? The UITableViewDiffableDataSource class has two generic types, one for the section identifier and one for the item. For both types, it is required to conform to the Hashable protocol. Since the Restaurant type doesn&#39;t conform to Hashable, Xcode shows the error.</p><p>You may wonder why this error only shows up for this newly created Restaurant type. We didn&#39;t see this kind of error when using the String type. The reason is that the Swift standard types, such as String and enum, already conform to Hashable. For the Restaurant struct, however, we have to adopt the Hashable manually.</p><p>You do not need to write extra code to implement the protocol. All you need to do is declare the conformance like this:</p><pre>struct Restaurant: Hashable {<br>    var name: String = &quot;&quot;<br>    var type: String = &quot;&quot;<br>    var location: String = &quot;&quot;<br>    var image: String = &quot;&quot;<br>    var isFavorite: Bool = false<br>}</pre><p>This is a built-in feature of Swift. Since all the properties of the Restaurant struct are Hashable, the compiler will automatically generate the required code for adopting the Hashable protocol.</p><p>This should fix all the errors. You can now run your app. The look &amp; feel of the app is exactly the same as before. However, we have refactored the code to use the new Restaurant struct. By combining multiple arrays into one, the code is now cleaner and more readable.</p><h3>Organizing Your Xcode Project Files</h3><p>As we continue to build our app, we will create even more files in the project folder. Therefore, I want to take this chance to show you a technique to better organize our projects.</p><p>Let’s first look at the project navigator. All files you have created are placed at the top level of the FoodPin folder. As you add more files, it will be getting more difficult to locate your desired file. To better organize your project files, Xcode provides a <em>group</em> feature that lets you organize the files by group/folder.</p><p>There are a number of ways to group your files. You may group them by features or functions. One good practice is to group them by their responsibilities in MVC (Model-View-Controller). Say, for view controllers, they will be grouped under Controller. Model classes like Restaurantwill be grouped under Model. For custom views like RestaurantTableViewCells, they will be put under a group named View.</p><p>To create a group in the project navigator, right click the FoodPin folder and select <em>New Group</em> to create a new group. Name it Controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAfD_DAd0GMy0P4bAucedg.png" /><figcaption><em>Figure 11–8. Right click FoodPin to create a new group</em></figcaption></figure><p>Next, select RestaurantTableViewController.swift and drag it to the Controller group.</p><p>Repeat the same procedure to group other files like that shown in figure 11–9 (left). If you open your project folder in Finder, you will find that all files are nicely organized into folders (see figure 11–9 (right)). Each of which corresponds to the specific group in your Xcode project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCYnf-tcZC1QjRPN_VzvrA.png" /><figcaption><em>Figure 11–9. Organizing project files into groups (left), Each group is a subfolder of the FoodPin folder (right)</em></figcaption></figure><p>Even if you have moved the files to different folders, you can still run the projects without any changes. Hit the Run button and try it out.</p><h3>Documenting and Organizing Swift Code with MARK</h3><blockquote><em>“Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. …[Therefore,] making it easy to read makes it easier to write.” ― Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship</em></blockquote><p>Other than project files, there are some best practices to organizing the source code better. Here I am going to show you a powerful technique to organize your Swift code into useful and easy to read sections.</p><p>As you know, those lines of code which begins with // are comments. Comments serve as a note to yourself or other developers (if you are working in a team), providing extra information (e.g. intent) about the code. The primary purpose is just to make your code more easy to understand.</p><pre>// Add &quot;Reserve a table&quot; action</pre><p>You may have noticed that some comments have the // MARK: marker. Here is an example:</p><pre>// MARK: - UITableViewDelegate Protocol</pre><p>MARK is a special comment marker in Swift for organizing your code into easy-to-navigate sections. Say, for the RestaurantTableViewController class, some of the methods are related to the UITableViewDelegate protocol. And, some are related to view controller life cycle or the data source. We can then add the MARK comment to separate them into sections.</p><pre>// MARK: - View controller life cycle<br><br>override func viewDidLoad() {<br><br>    .<br>    .<br>    .<br>}<br><br>// MARK: - UITableView Diffable Data Source<br><br>func configureDataSource() -&gt; UITableViewDiffableDataSource&lt;Section, Restaurant&gt; {<br><br>    .<br>    .<br>    .<br>}<br><br>// MARK: - UITableViewDelegate Protocol<br><br>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br><br>    .<br>    .<br>    .<br>}</pre><p>Now when you click the jump bar on top of your editor window, you can see the methods are organized into different meaningful sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dX7KF6WTdNYArs-ejoLhA.png" /><figcaption><em>Figure 11–10. Organizing your Swift code with MARK</em></figcaption></figure><h3>Summary</h3><p>Congratulations if you made it this far. I hope you’re not bored by the chapter. What I have covered is the basics of Object Oriented Programming. I also showed you some techniques for organizing your code and project files.</p><p>There are a lot more about the OOP concepts, such as polymorphism. However, we do not have time to discuss in-depth in this book. If you want to become a professional iOS developer, check out the references to learn more. It’ll take you a lot of practices to truly pick up OOP. Anyhow, if you manage to finish this chapter, this is a good start.</p><p>For reference, you can download the complete Xcode project from</p><p><a href="https://drive.google.com/drive/folders/1DlQwLGamnu5jedMp5iF6-QHnl_eWNN-P?usp=share_link">FoodPin - Google Drive</a></p><p>In the next chapter, base on what we’ve learned, you’ll continue to tweak the detail view screen of the FoodPin app. It’s going to be fun!</p><h3>Further References</h3><p>Swift Programming Language — Classes and Structures <a href="https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html">https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html</a></p><p>Swift Programming Language — Initialization <a href="https://docs.swift.org/swift-book/LanguageGuide/Initialization.html">https://docs.swift.org/swift-book/LanguageGuide/Initialization.html</a></p><p>Swift Programming Language — Inheritance <a href="https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html">https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html</a></p><p>Object Oriented Programming from MIT Open Courseware <a href="https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/resources/lecture-8-object-oriented-programming/">https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/resources/lecture-8-object-oriented-programming/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f5bf8410f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 - Displaying Alerts with UIAlertController and Handling Table View Selection using UIKit]]></title>
            <link>https://medium.com/@thanhtra.sqcb/7-displaying-alerts-with-uialertcontroller-and-handling-table-view-selection-using-uikit-15adaa97aa8f?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/15adaa97aa8f</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 10:42:33 GMT</pubDate>
            <atom:updated>2023-03-02T10:42:33.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTniUX4maJCqIzfCxvSBaQ.png" /></figure><p>Are you able to complete the previous exercise and create the custom table view? No worries if you can’t. I will go through the solution with you in this chapter and introduce some new layout techniques. Up till now, we only focus on displaying data in a table view. I guess you may wonder how we can interact with the table view and detect row selections. This is what we will also discuss in this chapter.</p><p>To begin, first download the complete project we built in the previous chapter</p><p><a href="https://drive.google.com/drive/folders/1HpridFBuTdaPqRNInJYxky2nq53L_oqF?usp=share_link">FoodPin (1) - Google Drive</a></p><p>We will continue to enhance the app and make it even better. In brief, here are what we are going to implement:</p><ul><li>Add another prototype cell to the table view</li><li>Bring up a menu when a user taps a cell. The menu offers two options: <em>Reserve a table</em> and <em>Mark as favorite</em>.</li><li>Display a heart icon when a user selects <em>Mark as favorite</em>.</li></ul><p>Through implementing these new features, you will also learn how to use two prototype cells and use UIAlertController to display alerts in iOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFzGx36vUYxUR4gAGHiIqA.png" /><figcaption><em>Figure 10–1. Sample alerts in Shortcut and Medium apps</em></figcaption></figure><h3>Building a more Elegant Cell Layout</h3><p>Previously, I had an exercise for you and asked you to redesign the prototype cell to make the cell layout look like that shown in figure 10–2. I hope you already tried to figure out the solution. Even if you couldn’t find a way to design the cell, I appreciate your effort. It is not an easy exercise for beginners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0WMssempwTkP241pRE0CA.jpeg" /><figcaption><em>Figure 10–2. Redesigning the table view cell</em></figcaption></figure><p>Now let’s see how to design the cell layout. Assuming you have already downloaded the project and open it in Xcode, select Main and switch over to Interface Builder. Instead of deleting the existing cell layout, we will create another prototype cell for the new design. That&#39;s right! You can create multiple prototype cells in the same table view. The only requirement is that each of the prototype cell should have a distinct identifier.</p><p>In the document outline, select <em>Table View</em> and then open the Attributes inspector. Here, change the value of the <em>Prototype Cells</em> option from 1 to 2. You will immediately see a new prototype cell added to the table view with the same cell layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzcTe7CMaUfHlg2ueH8szw.png" /><figcaption><em>Figure 10–3. Adding a new prototype cell</em></figcaption></figure><p>At the same time, Xcode displays an error indicator in Interface Builder. If you click the error indicator, Xcode complains that the two prototype cells have the same identifier which is not allowed. Now select the new prototype cell and change its identifier in the Attributes inspector. Let’s name it favoritecell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V5JnIiED80UsKBGKbH8Bg.png" /><figcaption><em>Figure 10–4. Changing the identifier for the new prototype cell</em></figcaption></figure><p>Once you made the change, the Xcode error disappears. Now it’s time to redesign the new cell. You do not delete all the elements and create the new cell from scratch because we still need both the image view and the labels. Instead, we are going to rearrange the cell layout.</p><p>First, select the favoritecell and go to the Size inspector. Delete the height value (i.e. 140) and hit return. Xcode will then change the size of the cell automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BowdHRv1HORMDpzdbA2jLw.png" /><figcaption><em>Figure 10–5. Setting the row height to automatic</em></figcaption></figure><p>Next, select the root Stack View of the favoritecell. In the Attributes inspector, change the <em>Axis</em> option from <em>Horizontal</em> to <em>Vertical</em> and you will see a new cell layout. This is one of the benefits of Stack View. It makes it so easy to rearrange the layout of the embedded components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XeXwG_qC-I9LVq_J4Bdcw.png" /><figcaption><em>Figure 10–6. Changing the axis of the stack view</em></figcaption></figure><p>With the new design, we no longer fix the width of the image view. Therefore, select the width constraint of the image view and hit delete to remove it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bShdjANTC223Wb1_hbWiww.png" /><figcaption><em>Figure 10–7. Delete the width constraint of the image view</em></figcaption></figure><p>We also want to make the image a little bit bigger. So, select the height constraint of the image view and change its constant in the Attributes inspector to 200.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*damjycpQMyEx218YJN43WQ.png" /><figcaption><em>Figure 10–8. Changing the height constraint of the image view</em></figcaption></figure><p>Meanwhile, the image view doesn’t scale to take up the width of the stack view. This is due to a setting in the root Stack view. Now select the stack view again and change its alignment from <em>Leading</em> to <em>Fill</em>. The image view should automatically expand. To make the cell look a little bit better, you can also change the spacing value from 20 to 5. To fix the layout error (did you notice the red indicator in the document outline?), change the <em>Distribution</em> option from <em>Fill</em> to <em>Equal Spacing</em>. This tells the stack view to maintain an equal spacing between the subviews without resizing the subviews themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5nEW-ZFC2GPxGiNr8M_Ow.png" /><figcaption><em>Figure 10–9. Changing the settings of the stack view</em></figcaption></figure><p>The cell layout now looks nearly the same as the one shown in figure 10.2. However, if you take a closer at the cell in the figure, the labels are indented slightly. How can you cater for this kind of indentation in a stack view?</p><p>Now select the stack view that holds the labels and go to the Size inspector. You can indent the stack view by setting the Layout Margins. Change the value of <em>Layout Margins</em> to <em>Language Directional</em> and set both leading &amp; trailing to 20 points. This should indent the label stack view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9uan9Up1w_GTh8ecswZjw.png" /><figcaption><em>Figure 10–10. Changing the settings of the stack view</em></figcaption></figure><p>If you run the app, it would still show the old design. This is we are still referring to the datacell in the code. To use the new cell layout, open RestaurantTableViewController.swiftand change the cellIdentifier constant in configureDataSource():</p><pre>let cellIdentifier = &quot;favoritecell&quot;</pre><p>Instead of using datacell, we tell the table view to use the new favoritecell. Now you are ready to test the app. Choose any of the iPhone simulators and hit the Play button. Your app should show you a brand new look. If you want to remove the separator between the cells, insert this line of code in the viewDidLoad() method:</p><pre>tableView.separatorStyle = .none</pre><p>What happens if you want to switch back to the old design? Yes! You just need to change the cellIdentifier back to datacell. This is how you can create multiple prototype cells and apply different design. In later chapters, I will teach you how to show two different cell layouts in the same table view.</p><h3>Understanding the UITableViewDelegate Protocol</h3><p>Now let’s move onto the next topic and discuss how you can detect a touch on the table view. When we first built the SimpleTable app in Chapter 8, we adopted two delegates, UITableViewDelegate and UITableViewDataSource, in the RestaurantTableViewController class. While we have a lengthy discussion on replacing the UITableViewDataSource protocol with UITableViewDiffableDataSource, I barely mentioned about the UITableViewDelegate protocol.</p><p>As said before, the delegate pattern is very common in iOS programming. Each delegate is responsible for a specific role or task to keep the system simple and clean. Whenever an object needs to perform a certain task, it depends on another object to handle it. This is usually known as “separation of concerns” in software design.</p><p>The UITableView class applies this design concept. The UITableViewDelegate protocol is designed to take care the configuration of the section headings and footers of the table view, as well as, handling cell selections and cell reordering. Therefore, to manage the row selection, we will need to adopt the UITableViewDelegate protocol and implement its methods.</p><h3>Looking Up the Documentation</h3><p>Before implementing the methods, you may wonder:</p><p><em>How do we know which methods in UITableViewDelegate to implement?</em></p><p>The answer is “Read the documentation”. You’re granted free access to the Apple’s official iOS developer reference (<a href="https://developer.apple.com/documentation/">https://developer.apple.com/documentation/</a>). As an iOS developer, you need to get used to reading the API documentation. There is no single book on earth to cover everything about the iOS SDK. Most of the time when we want to learn more about a class or a protocol, we have to look up to the API document.</p><p>Apple provides a simple way to access the documentation in Xcode. You can press and hold the <em>option</em> key and click on the class name to bring up the documentation. Alternatively, you can use the keyboard shortcut control-command-? and then place the cursor over a class or a protocol (e.g. UITableViewController). This brings up a popover showing the details of the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFjnjuywjzSevnWzGJej3w.png" /><figcaption><em>Figure 10–11. Accessing the API documentation by using a shortcut key</em></figcaption></figure><p>Scroll down and you will see the “Open in Developer Documentation” link. Click it to bring up the documentation browser. Here, you’ll find all the usage of the class. If you scroll down to the end of the document, you should see a section named “Conforms To” that lists out all the protocols that this class adopts. One of them is the UITableViewDelegate protocol. Click it to access the documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*665tD8osfznvHmVv9gzPlQ.png" /><figcaption><em>Figure 10–12. UITableViewController Documentation</em></figcaption></figure><p>By glancing through the document, you will find the methods below for managing row selections:</p><ul><li>func tableView(UITableView, willSelectRowAt: IndexPath) -&gt; IndexPath?</li><li>func tableView(UITableView, didSelectRowAt: IndexPath)</li></ul><p>Both methods are designed for row selections. The only difference is that the first method is called when a specified row is about to be selected. You may use this method to prevent the selection of a particular cell from taking place. Typically, you use the tableView(_:didSelectRowAt:) method. It is called after the user selects a row, to handle the row selection. We will implement this method to perform additional tasks (e.g. bringing up a menu) after a row is selected.</p><h3>Managing Row Selections by Implementing the Protocol</h3><p>Okay, that’s enough for the explanation. Let’s move onto the interesting part and write some code. In the FoodPin project, open the RestaurantTableViewController.swift file and implement the tableView(_:didSelectRowAt:) method in the RestaurantTableViewControllerclass:</p><pre>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br><br>    // Create an option menu as an action sheet<br>    let optionMenu = UIAlertController(title: nil, message: &quot;What do you want to do?&quot;, preferredStyle: .actionSheet)<br><br>    // Add actions to the menu<br>    let cancelAction = UIAlertAction(title: &quot;Cancel&quot;, style: .cancel, handler: nil)<br>    optionMenu.addAction(cancelAction)<br><br>    // Display the menu<br>    present(optionMenu, animated: true, completion: nil)<br>}</pre><p>First, what’s the override keyword? The documentation already tells us that the UITableViewController class adopted the UITableViewDelegate protocol and provided a default implementation for the method. Now we are <em>overriding</em> this method with our own code in RestaurantTableViewController. To override a method of a superclass, we add the overridekeyword at the very beginning of the method. When you do this, it&#39;s just like saying, &quot;Hey, don&#39;t use the default method implementation. Use mine.&quot;</p><p>The code above creates an option menu by instantiating a UIAlertController object. When a user taps any rows in the table view, this method will be called automatically to bring up an action sheet showing a <em>What do you want to do</em> message and a <em>Cancel</em> button. Try to run the project to have a quick test. The app should now be able to detect a touch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6P7T2nsAjPQXd0P0Qj9Cg.png" /><figcaption><em>Figure 10–13. Displaying an action sheet</em></figcaption></figure><h3>Understanding UIAlertController</h3><p>Before we move on, let me talk more about the UIAlertController class. The UIAlertController class was first introduced in iOS 8 to replace both UIAlertView and UIActionSheet classes from older versions of iOS SDK. It is designed for displaying alert messages to a user.</p><p>Referring to the code snippet in the previous section, you can specify the style of the UIAlertController object through the preferredStyle parameter. The value we used is .actionSheet. Alternatively, you can set its value to .alert which gives you another alert style. Figure 10-14 displays the sample alert styles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4J4xqyea5r8VGQ6viPOiug.png" /><figcaption><em>Figure 10–14. ActionSheet (left) and Alert (right)</em></figcaption></figure><p>Other than displaying a message to users, the alert controller usually associates with an action to give users a way to respond. In the code, we created a UIAlertAction object with a preferred title, style, and the block of code to execute for the action. The cancelAction object has the title Cancel and is set to use the .cancel style. There is nothing to perform when a user selects the cancel action. Thus, the handler is set to nil. After the UIAlertAction object is created, you can assign it to the alert controller by using the addAction method.</p><p>When the alert controller is configured properly, you present it modally using the presentmethod:</p><pre>present(optionMenu, animated: true, completion: nil)</pre><p>This is how you use the UIAlertController class to present an alert on screen. As a beginner, you may have a couple of questions in mind:</p><ul><li>How do I know the available values of the preferredStyle parameter when creating a UIAlertController object?</li><li>The dot syntax looks new to me. Shouldn’t it be written as UIAlertControllerStyle.actionSheet?</li></ul><p>Both are good questions.</p><p>For the first question, again the answer is “Refer to the documentation”. In Xcode, you can place the cursor over the preferredStyle parameter and press control-command-?. Xcode will show the method declaration. You can further click UIAlertController.Style to read the API reference. UIAlertController.Style is an enumeration, which defines two possible values: actionSheet and alert. That said, the most convenient way to find out the available values is by typing a . after preferredStyle:. Xcode automatically shows you all the possible values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwcJseEiSUxPTP7RPzW5nQ.png" /><figcaption><em>Figure 10–15. The available UIAlertControllerStyle values</em></figcaption></figure><pre>Quick note: An enumeration is a common type in Swift that defines a list of possible values for that type. The UIAlertController.Style is a good example.</pre><p>Now let me answer the second question.</p><p>Normally we can refer to the values using UIAlertController.Style.actionSheet or UIAlertController.Style.alert. You can write the code like this when creating a UIAlertController:</p><pre>let optionMenu = UIAlertController(title: nil, message: &quot;What do you want to do?&quot;, preferredStyle: UIAlertController.Style.actionSheet)</pre><p>There is nothing wrong with the code above. Swift gives developers a shorthand and helps us type less code. Because the type of the preferredStyle parameter is already known (i.e. UIAlertController.Style), Swift lets you use a shorter dot syntax by omitting UIAlertController.Style. This is why we instantiate the UIAlertController object like this:</p><pre>let optionMenu = UIAlertController(title: nil, message: &quot;What do you want to do?&quot;, preferredStyle: .actionSheet)</pre><p>The same applies to UIAlertAction.Style. The UIAlertAction.Style is an enumeration with three possible values: <em>default</em>, <em>cancel</em> and <em>destructive</em>. When creating the cancelAction object, we also use the shorthand syntax:</p><pre>let cancelAction = UIAlertAction(title: &quot;Cancel&quot;, style: .cancel, handler: nil)</pre><h3>Adding Actions to the Alert Controller</h3><p>Now let&#39;s add two more actions to the alert controller:</p><ul><li><strong>Reserve a table action</strong> - A fake feature to demo how to present an alert message. We will not implement this feature but simply display an alert prompt on screen.</li><li><strong>Mark as Favorite action</strong> - When selected, this option marks the selected restaurant as a favorite restaurant.</li></ul><p>In the tableView(_:didSelectRowAt:) method, add the following code for the &quot;Call&quot; action. You can insert the code after the initialization of cancelAction:</p><p>In the code above, the reserveActionHandler object is new to you. As mentioned before, you can specify a block of code as the handler when creating a UIAlertAction object. The block of code will be executed when the user selects the action. Previously, we specify nil in the cancelAction object. That means we do not have any follow-up action for the <em>Cancel</em> button.</p><p>For the reserveAction object, it is a bit different. We assign it with reserveActionHandler. The code block displays an alert, telling the user that the feature is not yet available.</p><p>Technically, this block of code is known as <em>Closure</em> in Swift. Closures are self-contained blocks of functionality that can be passed around in your code. It is very similar to <em>blocks</em> in Objective-C. Like the example above, one way to provide the action closure is to declare it as a constant or a variable with the block of code as the value. The first part of the code block is identical to the definition of the handler parameter of UIAlertAction. The in keyword indicates that the definition of the closure&#39;s parameters and return type has finished, and the body of the closure will begin. Figure 10-16 illustrates the syntax of a closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYuFkqwHw4vAMkrZCBdFxQ.png" /><figcaption><em>Figure 10–16. How you write a closure</em></figcaption></figure><p>The code specified in the body of the closure shouldn’t be new to you. We create a UIAlertController to display the warning. However, instead of using the .actionSheet style, we use .alert. Later when you test the app, you will understand how an alert looks like.</p><p>Once we prepared the action handler, we create the UIAlertAction object and set its title to &quot;Reserve a table&quot;. Most importantly, we assign the reserveActionHandler to the action object, followed by adding the action object to the option menu.</p><pre>let reserveAction = UIAlertAction(title: &quot;Reserve a table&quot;, style: .default, handler: reserveActionHandler)<br>optionMenu.addAction(reserveAction)</pre><p>Next, insert the following lines of code for the <em>Mark as favorite</em> action:</p><pre>// Mark as favorite action<br>let favoriteAction = UIAlertAction(title: &quot;Mark as favorite&quot;, style: .default, handler: {<br>    (action:UIAlertAction!) -&gt; Void in<br>    let cell = tableView.cellForRow(at: indexPath)<br>    cell?.accessoryType = .checkmark<br>})<br>optionMenu.addAction(favoriteAction)</pre><p>The above code shows you another way to use closure. You can write the closure inline as a parameter of the handler.</p><pre>Optionals in Swift<br>Do you still remember what the question mark is for? If you&#39;ve studied chapter 2, I hope you can answer the question. The cell is known as an optional in Swift. As mentioned before, Optional is a new type introduced in Swift. It simply means &#39;there is a value&#39; or &#39;there isn&#39;t a value at all&#39;. The cell returned by tableView.cellForRow(at:) is an optional. To access the accessoryType property of the cell, you use the question mark. In this case, Swift will check if the cell has a value and allow you to set the value of accessoryType if the cell exists. In most cases, the autocomplete feature of Xcode automatically adds the question mark for you when accessing a property of an optional.</pre><p>When a user selects the “Mark as favorite” option, we add a checkmark to the selected cell. For a table view cell, the right part is reserved for an accessory view. There are four types of built-in accessory views including <em>disclosure indicator</em>, <em>detail disclosure button</em>, <em>checkmark</em> and <em>detail</em>. In this case, we use <em>checkmark</em> as the indicator.</p><p>The first line of the code block retrieves the selected table cell using indexPath, which contains the index of the selected cell. The second line updates the accessoryType property of the cell with a check mark.</p><p>By default, the checkmark will be displayed in blue. Optionally, you can change its color by setting the tintColor property of a cell. In the awakeFromNib() method of RestaurantTableViewCell, you can add a line of code to set the cell&#39;s tint color:</p><pre>override func awakeFromNib() {<br>    super.awakeFromNib()<br>    self.tintColor = .systemYellow<br>}</pre><p>Compile and run the app. Tap a restaurant and choose one of the actions, it’ll either show you a check mark or an alert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxNPxVU9266isIImPHKFiA.png" /><figcaption><em>Figure 10–17. Reserve a table and Mark as favorite actions</em></figcaption></figure><p>For now, when you select a row, the row is highlighted in gray and stayed as selected. Add the following code at the end of the tableView(_:didSelectRowAt:) method to deselect the row.</p><pre>tableView.deselectRow(at: indexPath, animated: false)</pre><p>Your final code snippet of the tableView(_:didSelectRowAt:) method should like this:</p><pre>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br><br>    // Create an option menu as an action sheet<br>    let optionMenu = UIAlertController(title: nil, message: &quot;What do you want to do?&quot;, preferredStyle: .actionSheet)<br><br>    // Add actions to the menu<br>    let cancelAction = UIAlertAction(title: &quot;Cancel&quot;, style: .cancel, handler: nil)<br>    optionMenu.addAction(cancelAction)<br><br>    // Add &quot;Reserve a table&quot; action<br><br>    let reserveActionHandler = { (action:UIAlertAction!) -&gt; Void in<br><br>        let alertMessage = UIAlertController(title: &quot;Not available yet&quot;, message: &quot;Sorry, this feature is not available yet. Please retry later.&quot;, preferredStyle: .alert)<br>        alertMessage.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default, handler: nil))<br>        self.present(alertMessage, animated: true, completion: nil)<br><br>    }<br><br>    let reserveAction = UIAlertAction(title: &quot;Reserve a table&quot;, style: .default, handler: reserveActionHandler)<br>    optionMenu.addAction(reserveAction)<br><br>    // Mark as favorite action<br><br>    let favoriteAction = UIAlertAction(title: &quot;Mark as favorite&quot;, style: .default, handler: {<br>        (action:UIAlertAction!) -&gt; Void in<br><br>        let cell = tableView.cellForRow(at: indexPath)<br>        cell?.accessoryType = .checkmark<br><br>    })<br>    optionMenu.addAction(favoriteAction)<br><br>    // Display the menu<br>    present(optionMenu, animated: true, completion: nil)<br><br>    // Deselect the row<br>    tableView.deselectRow(at: indexPath, animated: false)<br>}</pre><h3>We Hit a Bug</h3><p>The app looks great. If you look at it closely, however, there is a bug in the app. Say, you mark the “Cafe Deadend” restaurant using the <em>Mark as favorite</em> action. If you scroll down the table, you’ll find that another restaurant (e.g. Palomino Espresso) also contains a checkmark. What’s the problem? Why did the app add an extra checkmark?</p><blockquote><em>Like every programmer, I hate bugs especially when facing a project deadline. However it’s always the bugs that help me improve my programming skills. You’ll hit a lot of bugs too as you continue to learn. Just get used to it.</em></blockquote><p>The problem is due to cell reuse, that we have discussed in the earlier chapter. For example, the table view has 30 cells. For performance reasons, instead of creating 30 table cells, UITableViewmay just create 10 cells and reuses them as you scroll through the table. In this case, UITableView reuses the 1st cell (originally used for Cafe Deadend with a checkmark) for displaying another restaurant. In our code, we only update the image view and labels when the table view reuses the same cell. The accessory view is not updated. Thus, the next restaurant reusing the same cell shares the same accessory view. If the accessory view contains a checkmark, that restaurant will also carry a checkmark.</p><p>So how can we resolve the bug?</p><p>We have to find another way to keep track of the checked items. How about creating another array to save the checked restaurants? In the RestaurantTableViewController.swift file, declare a Boolean array:</p><pre>var restaurantIsFavorites = Array(repeating: false, count: 21)</pre><p>Bool is a data type in Swift that holds a Boolean value. Swift provides two Boolean values: <em>true</em>and <em>false</em>. We declare the restaurantIsVisited array to hold a collection of Bool values. Each value in the array indicates whether the corresponding restaurant is marked as &quot;Check-in&quot;. For example, we can look into the value of restaurantIsVisited[0] to see if Cafe Deadend is checked or not.</p><p>The values in the array are initialized to false. In other words, the items are unchecked by default. The above line of code shows you a way to initialize an array in Swift with repeated values. The initialization is the same as the following:</p><pre>var restaurantIsVisited = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]</pre><p>We have to make a couple of changes in order to fix the bug. First, we need to update the value of the Bool array when a restaurant is marked as favorite. Add a line of code in the handler of the reserveAction object:</p><pre>let favoriteAction = UIAlertAction(title: &quot;Mark as favorite&quot;, style: .default, handler: {<br>    (action:UIAlertAction!) -&gt; Void in<br><br>    let cell = tableView.cellForRow(at: indexPath)<br>    cell?.accessoryType = .checkmark<br><br>    self.restaurantIsFavorites[indexPath.row] = true<br>})</pre><p>The code is very straightforward. We update the value of the selected item from false to true.</p><p>Lastly, update the configureDataSource method and insert the following line of code in the closure of cellProvider:</p><pre>cell.accessoryType = self.restaurantIsFavorites[indexPath.row] ? .checkmark : .none</pre><p>This is a simplified way to write a if condition. The ? is known as the ternary conditional operator, an efficient shorthand for evaluating simple conditions. The purpose of this single code of code is exactly the same as the following:</p><pre>if self.restaurantIsFavorites[indexPath.row] {<br>    cell.accessoryType = .checkmark<br>} else {<br>    cell.accessoryType = .none<br>}</pre><p>Every time when the cell is rendered, we check if the restaurant to be displayed is marked as favorite. If the condition is true, we display a checkmark in the cell. Otherwise, just display nothing. Since we refer to the restaurantIsFavorites array to see if the restaurant should be marked, we can now display the accessory view correctly, even if the cell is reused.</p><p>Now, compile and run the app again. Your bug should now be resolved.</p><h3>Working with iPad</h3><p>Have you tried to run the app on iPad? It looks pretty well. However, since the cell stretches across the width of the device, you may find the cells are a bit too long especially when you turn the iPad device sideway.</p><p>From iOS 9 and onwards, you can use a property called cellLayoutMarginsFollowReadableWidthto adjust the cell width automatically. If you insert the following line of code to the viewDidLoadmethod like below, you can enable the option:</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    tableView.cellLayoutMarginsFollowReadableWidth = true<br>    .<br>    .<br>    .<br>}</pre><p>After the change, run the app on the iPad simulator again. You will immediately find the difference. It is up to you if you want to keep this option enabled or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qm4vA9sisdyQBDTfpfRG4A.png" /><figcaption><em>Figure 10–18. Table view with cellLayoutMarginsFollowReadableWidth disabled (left), Table view with cellLayoutMarginsFollowReadableWidth enabled (middle and right)</em></figcaption></figure><h3>We Hit Another Bug on iPad</h3><p>When you tap any of the table view cells on iPad, the app crashes and ends up with an error in console:</p><pre>Terminating app due to uncaught exception &#39;NSGenericException&#39;, reason: &#39;Your application has presented a UIAlertController (&lt;UIAlertController: 0x7ff068897400&gt;) of style UIAlertControllerStyleActionSheet from FoodPin.RestaurantTableViewController (&lt;FoodPin.RestaurantTableViewController: 0x7ff069704d20&gt;). The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller&#39;s popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem.  If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.&#39;<br>terminating with uncaught exception of type NSException<br>CoreSimulator 732.17 - Device: iPad Pro (11-inch) (2nd generation) (02AA483A-0CAA-4645-8B8F-90D3397769A3) - Runtime: iOS 14.1 (18A8394) - DeviceType: iPad Pro (11-inch) (2nd generation)</pre><p>In case that you can’t see the console message, go up to the Xcode menu and choose <em>View &gt; Debug Area &gt; Activate Console</em>. Take a look at figure 10–19 if you don’t know where the console is. The console message is very useful in helping you find out the root cause of the error. Whenever you experience an exception in your app, look into the console and dig out the error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-G3sZXLkTtiTI5EPKtqhjw.png" /><figcaption><em>Figure 10–19. Console message</em></figcaption></figure><p>According to the error message, a UIActionController of style .actionSheet will behave differently on iPad. Instead of presenting the alert controller modally, iOS will present the controller using the popover style.</p><p>The presentation process is automatically handled by iOS. When the following line of the code is called, iOS will check if the device is an iPhone or iPad.</p><pre>present(optionMenu, animated: true, completion: nil)</pre><p>If it is an iPhone, the alert controller will be presented modally. On iPad, the alert controller will be presented in the popover style using the UIPopoverPresentationController object stored in its popoverPresentationController property.</p><p>Now try to look into the error message again. Can you find out the root cause of the error?</p><blockquote><em>You must provide location information for this popover through the alert controller’s popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem.</em></blockquote><p>When presenting the activity view controller using the popover style, you have to configure the source view of its popoverPresentationController. The source view indicates the view containing the anchor rectangle for the popover. You will understand what it means after implementing the popover.</p><p>Now, insert the following code in the tableView(_:didSelectRowAt:) method and place the code after the instantiation of optionMenu:</p><pre>if let popoverController = optionMenu.popoverPresentationController {<br>    if let cell = tableView.cellForRow(at: indexPath) {<br>        popoverController.sourceView = cell<br>        popoverController.sourceRect = cell.bounds<br>    }<br>}</pre><p>When the app is run on iPhone, the popoverPresentationController property of the alert controller (i.e optionMenu) is set to nil. Conversely, it will store the popover presentation controller when the app is run on iPad. Therefore, we use if let to check if the popoverPresentationController property has a value. If yes, we configure its sourceView to the cell that triggers the action. Optionally, we set the sourceRect property to the cell&#39;s bounds, so that the popover will be originated from the center of the cell.</p><p>Test the app on the iPad simulator again. It should work now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sv2GBs41JZI-3MoDyWcokg.png" /><figcaption><em>Figure 11–20. Popover menu on iPad</em></figcaption></figure><h3>Exercise #1</h3><p>Presently the app doesn’t allow users to uncheck the checkmark. Think about how you can alter the code such that the app can toggle the checkmark. You’ll also need to show a different title for the <em>Remove from favorites</em> button if the selected cell is marked. It’s not too hard to make the changes. Take some time to work on the exercise. I’m sure you’ll learn a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZjmqUeWiByych_Bxk5wKg.png" /><figcaption><em>Figure 10–21. Removing a restaurant from favorites</em></figcaption></figure><h3>Exercise #2</h3><p>Instead of showing the default checkmark, replace it with a heart icon. Xcode has some built-in system images. After adding an image view, you can set the image to heart.fill to use the heart image built into the system. Figure 10-22 shows you the final layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xt6scSXjuMYuMghXhHPqVA.png" /><figcaption><em>Figure 10–22. Using a heart icon to replace the default checkmark</em></figcaption></figure><p>You are expected to modify both prototype cells (i.e. datacell and favoritecell) to add the heart icon. Another hint is that you can use the isHidden property of an image view to control its visibility. For example, you can set the isHidden property to true to hide the image view like this:</p><pre>cell.heartImageView.isHidden = true</pre><p>I encourage you to take some time to work on this exercise too because it will help you revise everything you learned so far.</p><h3>Summary</h3><p>At this point, you should have a solid understanding of how to create table view, customize table cells and handle table row selection. You’re ready to build a simple table view app on your own (e.g. a simple ToDo app). I always recommend you to create your own project. I don’t mean you have to start a big one. If you love to travel, create a simple app that displays a list of your favorite destinations. If you love music, create your own app that shows a list of your favorite albums. Just play around with Xcode, make mistake and learn along the way.</p><p>For reference, you can download the complete Xcode project from</p><p><a href="https://drive.google.com/drive/folders/11INMpxilC8oDnoUinC4uXHQF3S3OtNWG?usp=share_link">FoodPin-2 - Google Drive</a></p><p>For the solution of the exercise, you can download it from</p><p><a href="https://drive.google.com/drive/folders/1f3iFy3CnxRmi4OwN_2jDtRaaDUYLtr9b?usp=sharing">FoodPin-3 - Google Drive</a></p><p>In the next chapter, we’ll continue to explore table view and see how you can delete a table row.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15adaa97aa8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 - Customize Table Views Using Prototype Cell, Diffable Data Source and Dark Mode using UIKit]]></title>
            <link>https://medium.com/@thanhtra.sqcb/6-customize-table-views-using-prototype-cell-diffable-data-source-and-dark-mode-using-uikit-484912d9967a?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/484912d9967a</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 10:19:10 GMT</pubDate>
            <atom:updated>2023-03-02T10:19:10.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4ntQkn48-ki5fSArcmgCw.png" /></figure><p>In the previous chapter, we created a simple table-based app to display a list of restaurants using the basic cell style. In this chapter, we’ll customize the table cell and make it look more stylish. And, I will show a modern way to handle the data source of a table view. There are a number of changes and enhancements we are going to work on:</p><ul><li>Rebuild the same app using UITableViewController instead of UITableView</li><li>Use the new UITableViewDiffableDataSource to configure the data of the table view</li><li>Display a distinct image for each restaurant rather than showing the same thumbnail</li><li>Design a custom table view cell instead of using the basic style of table view cell</li><li>Test the app in dark mode</li></ul><p>You may wonder why we need to rebuild the same app. There are always more than one way to do things. Previously, we used UITableView to create the table view. In this chapter, we&#39;ll use UITableViewController and UITableViewDiffableDataSource to create a table view app. Will it be easier? Yes, it&#39;s going to be easier. Recalled that we needed to explicitly adopt both UITableViewDataSource and UITableViewDelegate protocols, UITableViewController has already adopted these protocols and established the connections for us. On top of this, it has all the required layout constraints right out of the box.</p><p>The UITableViewDiffableDataSource class was first introduced in iOS 13, which is a modern way to supply a table view with the data to display. You can still use the traditional way, which was discussed in chapter 8, to populate data into a table. This new approach replaces the UITableViewDataSource protocol and will make your life much easier to cope with data changes in a table view. As more devices are adopting iOS 13 (or up), the UITableViewDiffableDataSourceapproach will become the standard implementation of UITableView.</p><p>Starting from this chapter and onwards, you begin to develop a real-world app called <em>FoodPin</em>. It’s gonna be fun!</p><h3>Building a Table View App Using UITableViewController and UITableViewDiffableDataSource</h3><p>First, let’s see how to use UITableViewController to re-create the same SimpleTable app. Fire up your Xcode, and create a new project using the <em>App</em> template. Name the project <em>FoodPin</em> and fill in all the required options for the Xcode project, just like what you did in the previous chapter.</p><pre>Quick note: We&#39;re building a real app, so let&#39;s give it a better name. Feel free to use other names if you want. Also, make sure you use your own organization identifier. Otherwise, you can&#39;t test your app on a real iPhone.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGxXqzqcV9zVS8RdcVZzYg.png" /></figure><p>Once you create the Xcode project, select the Main storyboard and jump to the Interface Builder editor. As usual, a default view controller is generated by Xcode.</p><p>This time, we will not use the default controller. Select the view controller, and press the delete key to delete it. The view controller is associated with ViewController.swift. We do not need it either. In the Project Navigator, select the file and hit the delete button. Select &quot;Move to Trash&quot; when prompted. This will completely delete the file.</p><p>Go back to Interface Builder. We will design the UI using iPhone 14 Pro, so change the device to <em>iPhone 14 Pro</em> using the configuration bar.</p><p>Next, open the Object library and search for “Table”. Then drag a Table View Controller (i.e. UITableViewController) from the library and place it in the storyboard. You have to designate that controller as the initial view controller. This tells iOS that the table view controller is the first view controller to load. All you need to do is go to the Attributes inspector, and tick the Is Initial View Controller option. You&#39;ll then see an arrow pointing to the table view controller (see figure 9-2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3vboQM9znBOVOeeXUzEjQ.png" /><figcaption><em>Figure 9–2. Drag a Table View Controller from the Object library and set it as the initial view controller</em></figcaption></figure><p>We haven’t inserted any data into the table yet. If you compile and run the app now, you’ll end up with a blank table.</p><p>By default, the table view controller is associated with the UITableViewController class (Go to the Identity inspector to take a look). In order to populate our own data, we have to associate it with our own class.</p><p>Go back to the Project Navigator and right-click the FoodPin folder. Select “New File…” to create a new file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIJOreuRqt5RLdybxMJtyw.png" /><figcaption><em>Figure 9–3. Create a new file</em></figcaption></figure><p>Under the iOS category, choose <em>Cocoa Touch Class</em> as the template and click Next. Name the new class RestaurantTableViewController. Because we&#39;re working with a table view controller, change the value of &quot;Subclass of&quot; to UITableViewController. Keep the rest of the values intact, click &quot;Next&quot; and save it to the project folder. You should see the RestaurantTableViewController.swift file in the project navigator. </p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*za6bgcD9LD2qDyRgN-tkTA.png" /></figure><pre>Superclass and Subclass<br>If you&#39;re new to programming, you may wonder what a subclass is. Swift is an object oriented programming (OOP) language. In OOP, a class can be inherited by another class. In the example, the RestaurantTableViewController class inherits from the UITableViewController class. It inherits all the states and functionalities provided by the UITableViewController class. The RestaurantTableViewController class is known as a subclass (or child class) of UITableViewController. In other words, the UITableViewController class is referred as the superclass (or parent class) of RestaurantTableViewController.</pre><p>The table view controller in the storyboard has no idea about the RestaurantTableViewController class we just created. We have to assign the table view controller with the new custom class. Go to Main and select the table view controller. In the Identity inspector, set the custom class to RestaurantTableViewController and hit the return key to confirm the change. Now we have established a relationship between the table view controller in the storyboard and the new class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjZcbxNex5m-tLoFPW_1uw.png" /><figcaption><em>Figure 9–5. Set the custom class of the Table View Controller</em></figcaption></figure><p>There is one more thing to configure for the table view. In the document outline, expand <em>Table View</em> and select the table view cell. In the Attributes inspector, change the cell style to Basicand set the identifier to datacell. This is pretty much the same as what we have done in the previous chapter.</p><p>Okay, the user interface is ready. Let’s move onto the code. Select the RestaurantTableViewController.swift file in the Project Navigator. By default, Xcode still uses the traditional way to handle the data source of the table view. If you look into the RestaurantTableViewController.swift file, you should find these lines of code:</p><pre>// MARK: - Table view data source<br><br>override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>    // #warning Incomplete implementation, return the number of sections<br>    return 0<br>}<br><br>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>    // #warning Incomplete implementation, return the number of rows<br>    return 0<br>}</pre><p>As mentioned earlier, we will use a new approach (i.e. UITableViewDiffableDataSource) to populate the table data. You can delete the code above and remove those commented code. After the clean up, your RestaurantTableViewController class should be like this:</p><pre>class RestaurantTableViewController: UITableViewController {<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>    }<br><br>}</pre><p>Now we are ready to adopt the new approach to create the same table view as shown in the previous chapter. First, declare an instance variable, which is used for holding the table data.</p><pre>var restaurantNames = [&quot;Cafe Deadend&quot;, &quot;Homei&quot;, &quot;Teakha&quot;, &quot;Cafe Loisl&quot;, &quot;Petite Oyster&quot;, &quot;For Kee Restaurant&quot;, &quot;Po&#39;s Atelier&quot;, &quot;Bourke Street Bakery&quot;, &quot;Haigh&#39;s Chocolate&quot;, &quot;Palomino Espresso&quot;, &quot;Upstate&quot;, &quot;Traif&quot;, &quot;Graham Avenue Meats&quot;, &quot;Waffle &amp; Wolf&quot;, &quot;Five Leaves&quot;, &quot;Cafe Lore&quot;, &quot;Confessional&quot;, &quot;Barrafina&quot;, &quot;Donostia&quot;, &quot;Royal Oak&quot;, &quot;CASK Pub and Kitchen&quot;]</pre><p>Previously, we implemented the following required methods of the UITableViewDataSourceprotocol to provide the table data:</p><ul><li>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int</li><li>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell</li></ul><p>The new approach no longer requires us to deal with the UITableViewDataSource protocol and all the methods above. Instead, we have to create a UITableViewDiffableDataSource object to configure the table view cell and then create a NSDiffableDataSourceSnapshot object to tell the table view what data to display.</p><p>UITableView supports multiple sections, thus the UITableViewDiffableDataSource object also requires us to specify the number of sections and the cell configuration of each section. For the demo app, we only have one section. So, declare an enum variable in RestaurantTableViewController like this:</p><pre>enum Section {<br>    case all<br>}</pre><p>We use enum to define a new Section type. In the enumeration, it only has one case because the table has a single section. I name the case all, which means all records. But you can actually name it to whatever name you like. Anyway, let&#39;s keep it to all.</p><p>Now that we have defined the section, the next step is to create an instance of UITableViewDiffableDataSource. We will write a new function called configureDataSource() for this purpose. Insert the following code inside RestaurantTableViewController:</p><pre>func configureDataSource() -&gt; UITableViewDiffableDataSource&lt;Section, String&gt; {<br><br>    let cellIdentifier = &quot;datacell&quot;<br><br>    let dataSource = UITableViewDiffableDataSource&lt;Section, String&gt;(<br>        tableView: tableView,<br>        cellProvider: {  tableView, indexPath, restaurantName in<br>            let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)<br><br>            cell.textLabel?.text = restaurantName<br>            cell.imageView?.image = UIImage(named: &quot;restaurant&quot;)<br><br>            return cell<br>        }<br>    )<br><br>    return dataSource<br>}</pre><p>The function looks a bit complicated but if you study the code, some of the lines should be familiar to you. As you are pretty new to Swift, let me walk you through the code line by line. The first line is the function declaration. The symbol (-&gt;) means return and the type that follows is the type of returned object.</p><pre>func configureDataSource() -&gt; UITableViewDiffableDataSource&lt;Section, String&gt; {<br>  ...<br>}</pre><p>So, in the code above, we create a function named configureDataSource() which returns an instance of UITableViewDiffableDataSource&lt;Section, String&gt;.</p><p>What’s Section and String here?</p><p>UITableViewDiffableDataSource is a generic object which is capable to handle different types of section and item of a table view. The type Section and String inside the angle bracket indicated that we use the Section type for the table section and the String type for the table cell data. The reason why String type is used is that the restaurant name is of the type String.</p><p>Inside the configureDataSource() function, we create an instance of UITableViewDiffableDataSource. When initializing the object, it is required to provide the instance of table view that the data source is connected, plus the cell provider. Obviously, the data source will connect to the tableView of RestaurantTableViewController. The cellProvider parameter is where you set up each cell of the table view. In the closure of the cell provider, you have three parameters including tableView, indexPath, and restaurantName. The restaurantName here is the restaurant name of the current cell.</p><p>The code inside cellProvider is pretty much like those in the tableView(_:cellForRowAt)function you wrote in the previous chapter:</p><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br><br>    let cellIdentifier = &quot;datacell&quot;<br>    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)<br><br>    // Configure the cell...<br>    cell.textLabel?.text = restaurantNames[indexPath.row]<br>    cell.imageView?.image = UIImage(named: &quot;restaurant&quot;)<br><br>    return cell<br>}</pre><p>The core difference is that we have to figure out the restaurant name from the restaurantNamesarray using index path. For cellProvider, it already passes us the restaurant name to display.</p><p>Now that we have created the function for configuring the data source, declare the following variable in RestaurantTableViewController to use it:</p><pre>lazy var dataSource = configureDataSource()</pre><p>You may wonder why we add a modifier lazy before the variable declaration. If you try to omit the lazy keyword, Xcode will show you the following message:</p><p><em>“Cannot use instance member ‘configureDataSource’ within property initializer; property initializers run before ‘self’ is available”</em></p><p>In this case, you must declare the variable with the lazy modifier because its initial value cannot be retrieved until after the instance initialization completes.</p><p>Okay, we have configured the data source of the table view. That said, your app is not yet ready to display the restaurants. We still have one more step to implement before the data shows up in the table view. Update the viewDidLoad function like this:</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br><br>    tableView.dataSource = dataSource<br><br>    var snapshot = NSDiffableDataSourceSnapshot&lt;Section, String&gt;()<br>    snapshot.appendSections([.all])<br>    snapshot.appendItems(restaurantNames, toSection: .all)<br><br>    dataSource.apply(snapshot, animatingDifferences: false)<br>}</pre><p>We first assign our custom dataSource to the table view&#39;s data source. The final step is to create a snapshot of the data to display in the table view. The snapshot is an instance of NSDiffableDataSourceSnapshot. This line of code creates an empty snapshot using the section identifier type Section and item identifier type String:</p><pre>var snapshot = NSDiffableDataSourceSnapshot&lt;Section, String&gt;()</pre><p>With the empty snapshot, we call appendSections to add a section to the snapshot. Then we call appendItems to add all items in the restaurantNames array to the .all section. Lastly, we apply the snapshot to the data source.</p><p>Before you run the app, download the image pack from</p><p><a href="https://drive.google.com/drive/folders/1qOgFIZuWz4UEyaApQj1Yu-1LkbTN55m_?usp=share_link">simpletable-images1 - Google Drive</a></p><p>and drag all images to the Assets.xcassets. Now, hit the &quot;Run&quot; button and your FoodPin app should look the same as the one we built earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM059hOhkehaGBB4Ad7u_g.png" /><figcaption><em>Figure 9–6. A simple table app</em></figcaption></figure><p>This is how we use the UITableViewDiffableDataSource approach to present data in a table view. To recap, here is the steps we used with this new approach:</p><ol><li>Create an enum which indicates the table sections.</li><li>Create a UITableViewDiffableDataSource object to connect with your table and provide the configuration of the table view cells.</li><li>Assign the diffable data source to your table view.</li><li>Generate the current state of the table data by creating a snapshot</li><li>Call the apply() function of the data source to populate the data</li></ol><p>Comparing with the traditional approach, which adopt the UITableViewDataSource protocol, you may wonder which approach is preferred. In general, use the diffable data source approach to create your table view. While the code may be more difficult to understand, this modern way of table view implementation will save you a lot of work when you need to update or change the table data. And, I forgot to mention this approach can automatically animate the data change. You will understand what this means in later chapters.</p><h3>Display Different Thumbnails</h3><p>Did you go through the exercise in the previous chapter? I hope you’ve put your effort in it. In this section, we will modify the existing app to display different restaurant images. First, download another image pack from</p><p><a href="https://drive.google.com/drive/folders/1K7U8n8ZF0VR-dsYGdLoipjuRs8bto---?usp=share_link">simpletable-images2 (1) - Google Drive</a></p><p>and unzip it. Add all the images into the asset catalog (i.e. Assets.xcasset). The pack includes some food and restaurant images. If you like, you’re free to use your own images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhVRHrxpC8L7fho_zzf8SQ.png" /><figcaption><em>Figure 9–7. Adding restaurant images to the asset catalog</em></figcaption></figure><p>First, let’s declare a new array named restaurantImages for holding the file name of the restaurant images. Insert the following line of code in the RestaurantTableViewController class:</p><pre>var restaurantImages = [&quot;cafedeadend&quot;, &quot;homei&quot;, &quot;teakha&quot;, &quot;cafeloisl&quot;, &quot;petiteoyster&quot;, &quot;forkee&quot;, &quot;posatelier&quot;, &quot;bourkestreetbakery&quot;, &quot;haigh&quot;, &quot;palomino&quot;, &quot;upstate&quot;, &quot;traif&quot;, &quot;graham&quot;, &quot;waffleandwolf&quot;, &quot;fiveleaves&quot;, &quot;cafelore&quot;, &quot;confessional&quot;, &quot;barrafina&quot;, &quot;donostia&quot;, &quot;royaloak&quot;, &quot;cask&quot;]</pre><p>Note that the order of images are aligned with that of the restaurantNames.</p><p>Before we continue to modify the code, let’s revisit the code for displaying the thumbnails in table row:</p><pre>cell.imageView?.image = UIImage(named: &quot;restaurant&quot;)</pre><p>The above line of code, inside the cellProvider closure of the configureDataSource function, tells UITableView to display restaurant.jpg in each cell. In order to display a different image, we need to modify this line of code.</p><p>As explained before, one of the parameters provided by the cellProvider closure is indexPath. With the index path, you can use indexPath.row to find out which row is now being processed.</p><p>Therefore, in order to load the corresponding image of the restaurant, change the line of code in the configureDataSource function from:</p><pre>cell.imageView?.image = UIImage(named: &quot;restaurant&quot;)</pre><p>to:</p><pre>cell.imageView?.image = UIImage(named: self.restaurantImages[indexPath.row])</pre><p>After saving the changes, try to run your app again. Each restaurant should display its own image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYWD0O0pQdYmVZPlfpIKEw.png" /><figcaption><em>Figure 9–8. Loading the table view with different restaurant images</em></figcaption></figure><h3>Customize Table View Cells</h3><p>So far we use the <em>basic</em> cell type for the table view. We’re going to make it even better by customizing the table cells. Here is what we are going to do. We will redesign the table view cell such that it will be a bit bigger and display a larger restaurant image. Also, we will show more information about the restaurant such as location and type. On top of that, we will round the corners of the images. To give you a better idea about how the cell is customized, take a look at figure 9–9. The cell looks awesome, right? And, I forgot to mention that the table view will also look great in dark mode. </p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikhfN25QZYWKOJUpLn7aEw.png" /></figure><h3>Designing Prototype Cells in Interface Builder</h3><p>The beauty of prototype cells is that it allows developers to customize the cell right inside the table view controller. To build a custom cell, you simply add other UI controls (e.g. labels, image views) to the prototype cell.</p><p>First, let’s change the style of the cell. You can’t customize the cell when it’s set to the Basicstyle. Select the prototype cell and change the style from Basic to Custom in the Attributes inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rITqDOESHOon3VInP3EdsQ.png" /><figcaption><em>Figure 9–10. Changing the cell style from Basic to Custom</em></figcaption></figure><p>In order to accommodate a larger thumbnail, we have to make the cell a little bit bigger. You’ll need to change the row height of the prototype cell. Select the prototype cell and change the row height to 140.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7WZSSdoV9V74miksIm9LQ.png" /><figcaption><em>Figure 9–11. Changing the row height of the prototype cell</em></figcaption></figure><p>After altering the row height, open the Object library and drag an Image View object to the prototype cell. Adjust its size to 120x120 points. You can select the image view, click the Size inspector and change the attribute of <em>X</em>, <em>Y</em>, <em>Width</em> and <em>Height</em> like that shown in figure 9–12. Once you set the size of the image view, switch over to the Attributes inspector and set the <em>Content Mode</em> of the image view to Aspect Fill. Since our image view is not a perfect square, the image will look better in this mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TcNR3R5hIrZsAxRqKPu6HA.png" /><figcaption><em>Figure 9–12. Adding an image view to the prototype cell</em></figcaption></figure><p>Next, we will add three labels to the prototype cell:</p><ul><li><strong>Name</strong> — for restaurant name</li><li><strong>Location</strong> — for restaurant location (e.g. New York)</li><li><strong>Type</strong> — for restaurant type (e.g. tea house)</li></ul><p>To add a label, drag a Label object from the Object library to the cell. Name the first label <em>Name</em>. Instead of using the system font for the label, we’ll use a text style. I will explain to you the difference of a fixed font and a text style in later chapters. For now, just go to the Attributes inspector, and change the font to Text Styles - Title 2. To change the font to the <em>Title 2</em> style, click the T button of the font option and change the font from <em>System</em> to <em>Title 2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-X3BhwS62uVqJjEzA_hSw.png" /><figcaption><em>Figure 9–13. Adding name label to the prototype cell</em></figcaption></figure><p>Drag another label to the cell and name it <em>Location</em>. Change the font to Text Styles - Body. Lastly, create another label and name it <em>Type</em>. For this label, change the font style to Text Styles - Subhead and set the font color to System Gray Color.</p><p>I’ve covered stack views in chapter 6. Not only can you use stack views in a view controller, you can also apply stack views to layout the components in a prototype cell. Thus, instead of defining the layout constraints for each of the labels and the image view, we will use stack views to group them together.</p><p>First, hold the command key, and select the three labels. Click the Embed in button in the layout bar and then choose <em>Stack View</em> to embed them in a vertical stack view. Go to the Attributes inspector, and change the spacing of the stack view to 4. This will add a space between the labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VBv_GC56UtAKVPjwCWTPA.png" /><figcaption><em>Figure 9–14. Embedding the labels using stack view</em></figcaption></figure><p>Next, select both the image view and the stack view that we have just created. Click the Embed in button and choose <em>Stack View</em> to embed them into a horizontal stack view. You can go up to the Attribute inspector, and change the spacing option to 20. Awesome, right? You can nest stack views to create complex layouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JLuEtoV5CNNs0gtYq1byA.png" /><figcaption><em>Figure 9–15. Combining the label stack view and the image view into a horizontal stack view</em></figcaption></figure><p>Again, it doesn’t mean you do not need to use auto layout. We still need to define the layout constraints for the stack view. Figure 9–16 depicts the layout requirements of the cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFdOea1bcZebBNcWQLBsDA.png" /><figcaption><em>Figure 9–16. The layout requirement of the prototype cell</em></figcaption></figure><p>In brief, we want the cell content (i.e. the stack view) is confined to the viewable area of the cell. This is why we’re going to define a spacing constraint for each side of the stack view. On top of this, the size of image view should be fixed to 120x120 points.</p><p>Now select the stack view and click the <em>Add New Constraints</em> button in the layout bar. Set the values of the top, left, bottom and right sides to 0, 0, 0 and 0 respectively. Also, make sure the <em>Constrain to margins</em> option is checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jp-w-7UwxiWgSXFoycclig.png" /><figcaption><em>Figure 9–17. Adding spacing constraints for the stack view</em></figcaption></figure><p>Once you add the 4 constraints, the stack view should be resized automatically. Next, we need to add a couple of constraints to control the size of the image view. In the document outline, drag horizontally from the image view to itself. In the pop over menu, hold shift key and choose both “width” and “height” options. Press enter to confirm. This ensures the size of the image view is fixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSA3Eo8H3To8pCN-qPX3KA.png" /><figcaption><em>Figure 9–18. Adding the width and height constraints for the image view</em></figcaption></figure><p>Cool! You’ve completed the layout of the prototype cell. Let’s move on and write some code.</p><h3>Creating a Class for the Custom Cell</h3><p>So far, we’ve designed the table cell. But how can we change the label values of the prototype cell? These values are supposed to be dynamic. By default, the prototype cell is associated with the UITableViewCell class. You can select the datacell in document outline and then go to the Identity inspector to reveal the association.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-h3iArBOnHSBsiufV34asQ.png" /><figcaption><em>Figure 9–19. The default class of a table view cell is set to UITableViewCell</em></figcaption></figure><p>In order to update the cell data, we’re going to create a new class, which extends from UITableViewCell, for the prototype cell. We want to create a custom version of UITableViewCellthat associates with the custom cell in Interface Builder.</p><p>As usual, right click the “FoodPin” folder in Project Navigator and select “New File…”. After selecting the option, Xcode prompts you to select a template. Since we need to create a new class for the custom table view cell, select “Cocoa Touch Class” and click “Next”. Fill in RestaurantTableViewCell as the class name and set the value of &quot;Subclass of&quot; to UITableViewCell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgw9ToYQrxLSW2aVIkBifQ.png" /><figcaption><em>Figure 9–20. Creating a new class for the custom table view cell</em></figcaption></figure><p>Click “Next” and save the file in the FoodPin project folder. Xcode should create a file named RestaurantTableViewCell.swift in the Project Navigator.</p><p>Next, declare the following outlet variables in the RestaurantTableViewCell class:</p><pre>@IBOutlet var nameLabel: UILabel!<br>@IBOutlet var locationLabel: UILabel!<br>@IBOutlet var typeLabel: UILabel!<br>@IBOutlet var thumbnailImageView: UIImageView!</pre><p>The RestaurantTableViewCell class serves as the view model of the custom cell. In the cell, we have 4 properties that are changeable:</p><ul><li>thumbnail image view</li><li>name label</li><li>location label</li><li>type label</li></ul><p>The view model stores and provides the values for the cell to display. Each of them is required to connect with the corresponding user interface object in Interface Builder. By connecting the source code with the UI objects, we can change the values of UI objects dynamically.</p><p>This is a very important concept in iOS programming. Your UI in storyboard and code are separated. You design the UI in Interface Builder and write your code in Swift. If you want to change the value or properties of a UI element (e.g. label), you have to establish a connection between them such that an object in your code can obtain a reference to an object defined in a storyboard. In Swift, you use @IBOutlet keyword to indicate a property of a class, that can be exposed to Interface Builder. For properties annotated with the IBOutlet keywords, we call it <em>outlets</em>.</p><p>So in the above code, we declare four outlets. Each outlet is going to connect with its corresponding UI object. Figure 9–21 depicts the connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5idJ1NgLALMfRwaOcA_jtg.png" /><figcaption><em>Figure 9–21. Outlet connections</em></figcaption></figure><pre>@IBAction vs @IBOutlet<br>We&#39;ve used @IBAction to indicate action methods when developing the HelloWorld app. What&#39;s the difference between @IBAction and @IBOutlet? @IBOutlet is used to indicate a property that can be connected with a view object in a storyboard. For example, if the outlet is connected with a button, you can use the outlet to change the color or title of the button. On the other hand, @IBAction is used to indicate an action method that can be triggered by a certain event. For example, when a user taps a button, it can trigger an action method to do something.</pre><p>Before we can establish a connection between the outlets of RestaurantTableViewCell class and the prototype cell in Interface Builder. We have to first set the custom class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzcbqfSH5LQO3xJguSzhrQ.png" /><figcaption><em>Figure 9–22. Set the custom class of the prototype cell</em></figcaption></figure><p>As said earlier, the prototype cell is associated with the default UITableViewCell class. To assign the prototype cell with the custom class, select the cell in storyboard. In the Identity inspector, set the custom class to RestaurantTableViewCell (see figure 9-22).</p><h3>Establishing the Connections</h3><p>Next, we will establish the connections between the outlets and UI objects in the prototype cell. In Interface Builder, right click the cell (i.e. datacell) in the Document Outline view to bring up the Outlets inspector. Drag from the circle (next to thumbnailImageView) to the image view object in the prototype cell (see figure 9-23). Xcode automatically establishes the connection when you release the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5uGUVq2NrhK9jiyzdBIOg.png" /><figcaption><em>Figure 9–23. Connecting the outlet with the image view</em></figcaption></figure><p>Repeat the above procedures for the following outlets:</p><ul><li><strong>locationLabel</strong> — connects to the <em>Location</em> label the cell</li><li><strong>nameLabel</strong> — connects to the <em>Name</em> label of the cell</li><li><strong>typeLabel</strong> — connects to the <em>Type</em> label of the cell</li></ul><p>After you’ve made all the connections, the UI should look like the screenshot shown in figure 9–24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tyg43zedtQx5U5tVsJx2Lg.png" /><figcaption><em>Figure 9–24. The outlet connections</em></figcaption></figure><p>You can also switch back to RestaurantTableViewCell.swift to review the connections. If an outlet variable is connected, it will be indicated by a gray circle indicator. You can even click on the indicator to reveal the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*az_iAujmgsUF_TsvaxdQ1g.png" /><figcaption><em>Figure 9–25. A gray circle indicates the outlet is connected properly</em></figcaption></figure><h3>Updating the Cell Provider</h3><p>Finally, we come to the last part of the change. In the RestaurantTableViewController class, we&#39;re still using UITableViewCell (i.e. the default cell) to display the content. We need to modify a line of code to replace it with our custom cell. If you look into the existing implementation of the configureDataSource method, you should find this line of code:</p><pre>let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)</pre><p>I’ve explained the meaning of the dequeueReusableCell method in the previous chapter. It is flexible enough to return any cell type from the queue. By default, it returns a generic cell of a UITableViewCell type. How do I know that? I read the documentation. Xcode provides you a convenient way to read the documentation of the APIs. Hold <em>option</em> key, place the mouse cursor over dequeueReusableCell and then click on it. Xcode will show you the description of the method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ofZ9KPrB5MQkDfT1EJbzA.png" /><figcaption><em>Figure 9–26. A gray circle indicates the outlet is connected properly</em></figcaption></figure><p>In order to use the RestaurantTableViewCell class, it&#39;s our responsibility to &quot;convert&quot; the returned object of dequeueReusableCell to RestaurantTableViewCell. This conversion process is known as <em>downcasting</em>. In Swift, we use the as! keyword to perform a forced conversion. Therefore, change the line of code in configureDataSource() to the following:</p><pre>let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell</pre><pre>as! and as?<br>Downcasting allows you to convert a value of a class to its derived class. For example, RestaurantTableViewCell is a child class of UITableViewCell. The dequeueReusableCellWithIdentifier method always returns a UITableViewCell object. If a custom cell is used, this object can be converted to the specific cell type (e.g. RestaurantTableViewCell). Prior to Swift 1.2, you can just use the as operator for downcasting. However, sometimes the object may not be converted to a specified type. Therefore, from Swift 1.2 and onwards, Apple introduced two more operators: as! and as?. If you&#39;re quite sure that the downcasting can perform correctly, use as! to perform the conversion. In case you&#39;re not sure if the value of one type can be converted to another, use as? to perform an optional downcasting. You&#39;re required to perform additional checking to see if the downcasting is successful or not.</pre><p>I know you can’t wait to test the app, but we need to change a few more lines of code. The lines of code below set the values of restaurant name and image:</p><pre>cell.textLabel?.text = restaurantName<br>cell.imageView?.image = UIImage(named: self.restaurantImages[indexPath.row])</pre><p>Both textLabel and imageView are properties of the default UITableViewCell class. Because we&#39;re now using our own RestaurantTableViewCell, we need to use the properties of the custom class. Change the above lines to the following:</p><pre>cell.nameLabel.text = restaurantName<br>cell.thumbnailImageView.image = UIImage(named: self.restaurantImages[indexPath.row])</pre><p>Now you’re ready to go. Hit the Run button and test the app. Your app should look like the one shown in figure 9–27. Try to rotate the simulator. The app also works in landscape orientation. It is a huge improvement from the previous version of the app. We’re going to make it even better by rounding the corners of the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QV0Yxvp1VZeh3xzVnSEPQ.png" /><figcaption><em>Figure 9–27. FoodPin app with custom table view cells</em></figcaption></figure><h3>Rounding Image Corners</h3><p>Since the release of iOS 14 and macOS Big Sur, it made me feel that Apple favors to round the edges of UI elements. For this demo app, wouldn’t it be great to make all the restaurant images rounded corners? You do not need Photoshop to tweak the images. What you need is to write a couple lines of code.</p><p>Every view in the UIKit (e.g. UIView, UIImageView) is backed by an instance of the CALayerclass (i.e. layer object). The layer object is designed to manage the backing store for the view and handles view-related animations.</p><p>The layer object provides various attributes that can be set to control the visual content of the view such as:</p><ul><li>Background color</li><li>Border and border width</li><li>Shadow color, width, etc</li><li>Opacity</li><li>Corner radius</li></ul><p>The corner radius is the attribute, which we use to draw rounded corners. Xcode provides two ways to edit the layer properties. One of the approaches is make the change through Interface Builder. First, select the image view in the stack view. Go to the Identity inspector, click the Add button (+) in the lower left of the <em>User Defined Runtime Attributes</em> editor. A new runtime attribute appears in the editor. Double click on the <em>Key Path</em> field of the new attribute to edit the key path for the attribute. Set the value to cornerRadius and hit Return to confirm. Click on the <em>Type</em>attribute and choose Number. Lastly, set the value to 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVp3cWUzJCRQAYzqv39fsw.png" /><figcaption><em>Figure 9–28. Set the runtime attribute to make the corner round</em></figcaption></figure><p>When the image view is initialized, this runtime attribute will be automatically loaded to round the corners. There is one more thing you have to configure before the circular image works properly. Select the image view and go to the Attributes inspector. In the Drawing section, please make sure to enable the <em>Clip to Bounds</em> option. This causes the content to be clipped to the rounded corners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64cuB0ZHE2Cm3lFyHR3Xvw.png" /><figcaption><em>Figure 9–29. FoodPin app with circular images</em></figcaption></figure><p>Now compile and run the app. The UI looks even better, right? Without writing a line of code, we round the edge of the images. You’re free to alter the value of corner radius. Try to change the corner radius to 60 points and see what you get.</p><p>Other than using Interface Builder, you can also change the corner radius programatically. In RestaurantTableViewCell.swift, you can add a didSet code block for thumbnailImageView like this :</p><pre>@IBOutlet var thumbnailImageView: UIImageView! {<br>    didSet {<br>        thumbnailImageView.layer.cornerRadius = 20.0<br>        thumbnailImageView.clipsToBounds = true<br>    }<br>}</pre><p>didSet is known as a property observer in Swift. As its name suggests, the code block specified in didSet will be called every time a property&#39;s value is set. In the code above, when an image view is assigned, the didSet code block will be called to change the corner radius and set the clipsToBounds value to true.</p><p>To create a circular image, you can change the code snippet like this, which set the radius to half the width of the image view.</p><pre>@IBOutlet var thumbnailImageView: UIImageView! {<br>    didSet {<br>        thumbnailImageView.layer.cornerRadius = thumbnailImageView.bounds.width / 2<br>        thumbnailImageView.clipsToBounds = true<br>    }<br>}</pre><h3>Testing the App Using Dark Mode</h3><p>Since the release of iOS 13, Apple allows users to choose between light and dark system-wide appearance. When the user chooses to adopt Dark Mode, both the system and apps use a darker color palette for all screens and views. As an app developer, you should make sure your apps also comply with Dark Mode. There are multiple ways to test your app in Dark Mode.</p><p>While you are running the app on a simulator, you can click the <em>Environment Overrides</em> button to switch the appearance from light to dark. Once you enable the switch, the simulator is set to adopt Dark Mode. Our FoodPin app already looks great without any additional changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXJlE2_tSg5eA835D831gQ.png" /><figcaption><em>Figure 9–30. Redesigned Custom Table</em></figcaption></figure><p>Alternatively, you can directly change the setting of your simulator. On any of the simulators, go to <em>Settings &gt; Developer</em>. Turn the switch of the <em>Dark Appearance</em> option to ON to enable Dark Mode.</p><h3>Exercise #1</h3><p>As of now, the app simply displays “Location” and “Type” for all rows. As an exercise, I’ll leave it to you to fix the issue. Try to edit the source code to update the location and type labels. Below are the two arrays you need:</p><pre>var restaurantLocations = [&quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Hong Kong&quot;, &quot;Sydney&quot;, &quot;Sydney&quot;, &quot;Sydney&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;New York&quot;, &quot;London&quot;, &quot;London&quot;, &quot;London&quot;, &quot;London&quot;]<br><br>var restaurantTypes = [&quot;Coffee &amp; Tea Shop&quot;, &quot;Cafe&quot;, &quot;Tea House&quot;, &quot;Austrian / Causual Drink&quot;, &quot;French&quot;, &quot;Bakery&quot;, &quot;Bakery&quot;, &quot;Chocolate&quot;, &quot;Cafe&quot;, &quot;American / Seafood&quot;, &quot;American&quot;, &quot;American&quot;, &quot;Breakfast &amp; Brunch&quot;, &quot;Coffee &amp; Tea&quot;, &quot;Coffee &amp; Tea&quot;, &quot;Latin American&quot;, &quot;Spanish&quot;, &quot;Spanish&quot;, &quot;Spanish&quot;, &quot;British&quot;, &quot;Thai&quot;]</pre><h3>Exercise #2</h3><p>The previous exercise may be too easy for you. Here is another challenge. Try to redesign the prototype cell and see if you create an app like this (see figure 9–31).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0WMssempwTkP241pRE0CA.jpeg" /><figcaption><em>Figure 9–30. Redesigned Custom Table</em></figcaption></figure><p>As a hint, you can add the following line of code in viewDidLoad() to remove the cell separator:</p><pre>tableView.separatorStyle = .none</pre><h3>Summary</h3><p>Congratulations! You’ve made a huge progress. If you understand the ins and outs of cell customization, you’re ready to make some awesome UIs. Table view is the backbone for most iOS apps. Unless you’re building a game, you’ll probably implement a table view in one way or another when building your own apps. Table view customization may be a bit complex for some of you. So take some time to work on the exercises and play around with the code. Remember “learn by doing” is the best way to learn coding.</p><p>For reference, you can download the complete Xcode project from</p><p><a href="https://drive.google.com/drive/folders/1nipTAoAkEVObIuVbKM20OV7zl3AYVNsf?usp=share_link">FoodPin - Google Drive</a></p><p>If you can’t figure out how to complete the exercise, you can download the solution from</p><p><a href="https://drive.google.com/drive/folders/1MEDY12iQbRpIlzM3nK4aTe8gLVQW9j5d?usp=share_link">FoodPin-2 - Google Drive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=484912d9967a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 - Creating a Simple Table Based App using UIKit]]></title>
            <link>https://medium.com/@thanhtra.sqcb/5-creating-a-simple-table-based-app-using-uikit-23dafe52f5f6?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/23dafe52f5f6</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 09:46:27 GMT</pubDate>
            <atom:updated>2023-03-02T09:46:27.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPgHKgKV_9LezzDx0aqNzA.png" /></figure><p>Now that you have a basic understanding of prototyping and our demo app, we’ll work on something more interesting and build a simple table-based app using UITableView in this chapter. Once you master the technique and the table view customization (to be discussed in the next chapter), we’ll start to build the Food Pin app.</p><p>First of all, what exactly is a table view in an iPhone app? A table view is one of the most common UI elements in iOS apps. Most apps (except games), in some ways, make use of table view to display content. The best example is the built-in Phone app. Your contacts are displayed in a table view. Another example is the Mail app. It uses a table view to display your mail boxes and emails. Not only designed for listing textual data, table view allows you to present the data in the form of images. The TED, Google+ and Airbnb are also good examples. Figure 8–1 displays a few more sample table-based apps. Though they look different, all in some ways utilize a table view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4K_MWgjdT7JS0thOTWRnMA.png" /><figcaption><em>Figure 8–1. Sample table-based apps (left to right: Techcrunch, App Store, Product Hunt, and TED)</em></figcaption></figure><p>What we are going to do in this chapter is create a very simple table view and learn how to populate data (images and text) into it.</p><h3>Creating a SimpleTable Project</h3><blockquote><em>Don’t just read the book. If you’re serious about learning iOS programming, stop reading. Open your Xcode and code! This is the best way to learn programming.</em></blockquote><p>Let’s get started and create a simple app. The app is really simple. We’ll just display a list of restaurants in a plain table view. We’ll polish it in the next chapter. If you haven’t fired up Xcode, launch it, and create a new project using the <em>App</em> template under iOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zehrv8QPAuSdk_dQ_oHa2A.png" /><figcaption><em>Figure 8–2. Xcode Project Template</em></figcaption></figure><p>Click “Next” to continue. Again, fill in all the required options for the Xcode project:</p><ul><li><strong>Product Name: SimpleTable</strong> — This is the name of your app.</li><li><strong>Team:</strong> Just leave it as it is.</li><li><strong>Organization Name: AppCoda</strong> — It’s the name of your organization.</li><li><strong>Organization Identifier: com.appcoda</strong> — It’s actually the domain name written the other way round. If you have a domain, you can use your own domain name. Otherwise, you may use “com.”.</li><li><strong>Bundle Identifier: com.appcoda.SimpleTable</strong> — This field should be automatically generated by Xcode.</li><li><strong>Interface: Storyboard</strong> — Xcode now supports two ways to build UI. In this book, we use Storyboard.</li><li><strong>Language: Swift</strong> — Xcode supports both Objective-C and Swift for app development. As this book is about Swift, we’ll use Swift to develop the project.</li><li><strong>Use Core Data: [unchecked]</strong> — Do not select this option. You do not need Core Data for this simple project. We’ll explain Core Data in later chapters.</li><li><strong>Include Tests: [unchecked]</strong> — Do not select this option. You do not need unit tests for this simple project.</li></ul><p>Click “Next” to continue. Xcode then asks you where to save the <em>SimpleTable</em> project. Pick a folder on your Mac. Click “Create” to continue.</p><h3>Design the User Interface</h3><p>To present data in a table in an iOS app, all you need to use is the table view object. First, select Main to switch to the Interface Builder editor. Again, I prefer to use iPhone 14 Pro to design the UI. Select the device button and change it to iPhone 14 Pro. Open the Object library, look for the Table View object and drag it into the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cs9DXCDChpVRQ-V4QhhNuw.png" /><figcaption><em>Figure 8–3. Drag a table view from the Object library to the View</em></figcaption></figure><p>Resize the table view to fit the whole view. Next, go to the Attributes inspector (if it doesn’t appear in your Xcode, choose <em>View &gt; Inspectors &gt; Attributes</em>), change the number of Prototype Cells from 0 to 1. A prototype cell will appear in the table view.</p><p>Prototype cells allow you to easily design the layout of your table view cell. You can think of it as a cell template such that you can reuse it in all the table cells.</p><p>By default, a prototype cell comes with several standard cell styles including basic, right detail, left detail and subtitle. You can create your cell design or simply choose from the default style. In this example, we will use the basic style. For cell customizations, I will leave it to the next chapter.</p><p>Select the cell and then open the Attributes inspector. Change the cell style to <em>Basic</em>. This style is good enough to display a cell with both text and image. Additionally, set the identifier to datacell. This is a unique key for identifying the prototype cell. We&#39;ll use it later when writing code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qfxcyDYHYWE8JQMGC9S0A.png" /><figcaption><em>Figure 8–4. Prototype Cell in table view using Basic style</em></figcaption></figure><h3>Run Your App to Have a Quick Test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJN0vy7SAhD1QOxYIKXXbw.png" /><figcaption><em>Figure 8–5. A blank table view on the iPhone simulator</em></figcaption></figure><p>If you run the app to have a quick test, you should see a blank screen because we haven’t filled the table view with data.</p><p>So far we haven’t defined any layout constraints for the table view. To make the table view work for all different screen sizes, we need to add a few layout constraints. Now select the <em>Table View</em>in Interface Builder, click the <em>Add new constraints</em> button in the layout bar. Set the spacing of the top, left, right and bottom side to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SddgaPubYI_2RBM5lt4xXw.png" /><figcaption><em>Figure 8–6. Adding layout constraint to the table view</em></figcaption></figure><p>Make sure the bars are in solid red and the <em>Constrain to margins</em> option is unchecked. Then click the <em>Add 4 Constraints</em> button to add the constraints.</p><p>Here we define 4 spacing constraints for each side of the table view. The <em>Constrain to margins</em>option is unchecked. In this case, the spacing constraints will be relative to the edge of the view. This ensures that all sides of the table view will stretch to the edge of the view. In other words, your table view will automatically resize to fit all screen sizes.</p><p>If you tick the <em>Constrain to margins</em> option, it will still work. Figure 8–7 shows you how the safe area is adjusted when the option is enabled or disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBgN8dG7MqAAKxZuqzvwKQ.png" /><figcaption><em>Figure 8–7. The Safe Area layout guide varies based on the selection of the Constrain to Margins option</em></figcaption></figure><p>With the UI design ready, let’s move onto the core part and write some code to insert the table data.</p><h3>UITableView and its Protocols</h3><p>I mentioned at the very beginning of the book that other than Swift, you have to learn the APIs and foundation classes provided by the iOS SDK in order to build an app. These APIs and classes are organized into what-so-called <em>frameworks</em>. The UIKit framework is one of the most commonly used frameworks.</p><p>It provides classes to construct and manage your app’s user interface. All objects listed in the Object library of Interface Builder are provided by the framework. The Button object you used in the HelloWorld app, and the Table View object we’re working on right now are from the UIKit framework. While we use the term <em>Table View</em>, the actual class is <em>UITableView</em>. Simply put, every UI component in the Object library has a corresponding class. You can first select <em>Table View</em>, and then go to the Identity inspector to reveal the actual class name in the custom class section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zp_lZ-fG2JPChyVsIIgCEQ.png" /><figcaption><em>Figure 8–8. You can reveal the actual class in the Identity inspector</em></figcaption></figure><blockquote><em>I intentionally leave out the discussion of classes and methods to later chapters. If you have no ideas what a class is, don’t worry. Just think of it as a code template. I will explain it to you in later chapters.</em></blockquote><p>Now that you have an idea about the relationship between Table View and UITableView. We’ll write some code to insert the table data. Select ViewController.swift in the project navigator to open the file in the editor pane. Append , UITableViewDataSource, UITableViewDelegate after UIViewController to adopt the protocols.</p><p>As soon as you insert the code after UIViewController, Xcode detects an error. The red exclamation mark at the top-right corner of the code editor indicates that there is a problem. On top of that, Xcode highlights the line of code, and display a message telling you the details of the issue. The message is helpful for telling the cause of the problem and it also shows you the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqExI_rHOy4HVyWIidUTOA.png" /><figcaption><em>Figure 8–9. Implementing UITableViewDataSource and UITableViewDelegate protocols</em></figcaption></figure><p>Wait. Don’t click the <em>Fix</em> button yet. What does it mean by “Type ViewController does not conform to protocol UITableViewDataSource”?</p><p>The UITableViewDelegate and UITableViewDataSource are known as protocols in Swift. To display data in a table view, we have to conform to a set of requirements, defined in the protocols. Here, the ViewController class is the one that adopts the protocol, and implements all the mandatory methods.</p><p>It may be confusing. What are these protocols? Why protocols?</p><p>Well, let’s say you’re starting a new business. You hire a graphic designer to design your company logo. The designer is skilled and very capable of creating any kind of logo. But the designer can’t start the logo design right away. In the least, you need to provide the designer with some requirements such as company name, color preference, business nature before he/she can create a logo. However, you’re busy. You delegate the task to your personal assistant, and let the assistant deal with the designer directly, providing the designer with the logo requirements.</p><p>In iOS programming, the UITableView class is just like the graphic designer. It&#39;s flexible enough to display various kinds of data (e.g. image, text) in table form. You can use it to display a list of countries or contact names. Or in our project, we&#39;ll be presenting a list of restaurants with thumbnails.</p><p>But before UITableView can display the data for you, it requires someone to provide some basic information like:</p><ul><li>How many rows do you want to display in the table view?</li><li>What is the table data? For example, what do you want to display for row 2? What do you want to display in row 5?</li></ul><p>That “someone” is known as a delegate object. In the above analogy, the personal assistant is the delegate object. In iOS programming, it also applies the concept of delegation usually known as <em>delegation pattern</em>. An object relies on another object to perform a specific task. In our project, the ViewController is the delegate that provides the table data. Figure 8–10 illustrates the relationship of UITableView, the protocols and the delegate object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSPjNYoabrJfSkUKJ1btxg.png" /><figcaption><em>Figure 8–10. The relationship of UITableView, the protocols and the delegate object</em></figcaption></figure><p>So how do you tell UITableView what data to display? The UITableViewDataSource protocol is the key. It&#39;s the link between your data and the table view. The protocol defines a list of methods that you have to adopt.</p><p>Okay, what methods should I adopt? Now you are ready to click the <em>Fix</em> button in the error prompt shown in figure 8–9. As soon as you click the button, Xcode adds the following methods:</p><pre>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br><br>}<br><br>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br><br>}</pre><p>These are the two required methods for the UITableViewDataSource protocol.</p><p>All you need is to provide the implementation so that UITableView knows the total number of rows to display and the data for each row. The protocol also defines some optional methods that we&#39;ll not discuss it here.</p><p>The UITableViewDelegate protocol, on the other hand, deals with the appearance of the UITableView. All methods defined in the protocols are optional. They let you manage the height of a table row, configure section headings and footers, re-order table cells, etc. We will not change any of these methods in this example. We will leave that for a later chapter.</p><p>With some basic knowledge of protocols, let’s continue to code the app. Select ViewController.swift and declare a variable for holding the table data. Name the variable restaurantNames and insert the following line of code in the class:</p><pre>var restaurantNames = [&quot;Cafe Deadend&quot;, &quot;Homei&quot;, &quot;Teakha&quot;, &quot;Cafe Loisl&quot;, &quot;Petite Oyster&quot;, &quot;For Kee Restaurant&quot;, &quot;Po&#39;s Atelier&quot;, &quot;Bourke Street Bakery&quot;, &quot;Haigh&#39;s Chocolate&quot;, &quot;Palomino Espresso&quot;, &quot;Upstate&quot;, &quot;Traif&quot;, &quot;Graham Avenue Meats And Deli&quot;, &quot;Waffle &amp; Wolf&quot;, &quot;Five Leaves&quot;, &quot;Cafe Lore&quot;, &quot;Confessional&quot;, &quot;Barrafina&quot;, &quot;Donostia&quot;, &quot;Royal Oak&quot;, &quot;CASK Pub and Kitchen&quot;]</pre><p>In this example, we use an array to store the table data. If you forgot the syntax of an array, refer to chapter 2. The values are separated by commas and surrounded by a pair of square brackets.</p><p>When I said “insert the code in the class”, it means you have to declare the variable within the curly bracket of the class like this:</p><pre>class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {<br>     var restaurantNames = [&quot;Cafe Deadend&quot;, &quot;Homei&quot;, &quot;Teakha&quot;, &quot;Cafe Loisl&quot;, &quot;Petite Oyster&quot;, &quot;For Kee Restaurant&quot;, &quot;Po&#39;s Atelier&quot;, &quot;Bourke Street Bakery&quot;, &quot;Haigh&#39;s Chocolate&quot;, &quot;Palomino Espresso&quot;, &quot;Upstate&quot;, &quot;Traif&quot;, &quot;Graham Avenue Meats And Deli&quot;, &quot;Waffle &amp; Wolf&quot;, &quot;Five Leaves&quot;, &quot;Cafe Lore&quot;, &quot;Confessional&quot;, &quot;Barrafina&quot;, &quot;Donostia&quot;, &quot;Royal Oak&quot;, &quot;CASK Pub and Kitchen&quot;]<br>    .<br>    .<br>    .<br>}</pre><h3>Arrays for Absolute Beginners</h3><p>An array is a fundamental data structure in computer programming. You can think of an array as a collection of data elements. Consider the restaurantNames array in the above code, it represents a collection of String elements. You may visualize the array like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8QoVdiCZQj-C8sPpjIQ8A.png" /><figcaption><em>Figure 8–11. restaurantNames array</em></figcaption></figure><p>Each of the array elements is identified or accessed by an index. An array with 10 elements will have indices from 0 to 9. That means restaurantNames[0] returns the first item of the array.</p><p>Let’s continue to code. We adopt the two required methods of the UITableViewDataSourceprotocol like this:</p><pre>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>    // Return the number of rows in the section.<br>    return restaurantNames.count<br>}<br><br>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>    let cellIdentifier = &quot;datacell&quot;<br>    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)<br><br>    // Configure the cell...<br>    cell.textLabel?.text = restaurantNames[indexPath.row]<br><br>    return cell<br>}</pre><p>The first method is used to inform the table view the total number of rows in a section. You can simply call the count method to get the number of items in the restaurantNames array.</p><pre>Quick note: A table view can have multiple sections but there is only one by default.</pre><p>The second method will be called every time a table row is displayed. By using the indexPathobject, we can get the current row (indexPath.row). Here what we did is to retrieve the indexed item from the restaurantNames array, and assign it to the text label (cell.textLabel?.text) for display.</p><pre>Note: You may wonder what the question mark (?), next to textLabel, is for. Do you still remember optionals we discussed in chapter 2? Here textLabel is an optional. To access the property of textLabel, we have to first verify if textLabel has a value. You can use if let to perform the verification. Alternatively, you can place a question mark (?) after textLabel.</pre><p>Okay, but what is dequeueReusableCell in the second line of code?</p><p>The dequeueReusableCell method is used for retrieving a reusable table cell from the queue with the specified cell identifier. The datacell identifier is the one we defined earlier in Interface Builder.</p><p>You want your table-based app to be fast and responsive even when handling thousands of rows of data. If you allocate a new cell for each row of data instead of reusing one, your app will use excess memory and may result in a sluggish performance when the user scrolls the table view. Remember every cell allocation has a performance cost, especially when the allocation happens over a short period of time.</p><p>The screen real estate of iPhone is limited. Even if your app needs to display 1,000 records, the screen may only be able to fit 10 table cells at most. Therefore, why on earth would the app allocate a thousand table view cells instead of creating 10 table cells and reuse them? This would save tons of memory and make table view work more efficiently. For performance reasons, you should reuse table view cells instead of creating new ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1cICdDA7_uS1NIc8ps03Q.png" /><figcaption><em>Figure 8–12. Illustration showing how UITableView reuses table view cells</em></figcaption></figure><p>Now, let’s hit the “Run” button and test your app. Oops! The app still displays a blank table view just like before.</p><p>Why is it the table view still not showing the content as expected? We’ve written the code for displaying table data and implemented all required methods. But why the table view didn’t show the content as expected?</p><p>There is still one thing left.</p><h3>Connecting the DataSource and Delegate</h3><p>Even though the ViewController class has adopted the UITableViewDelegate and UITableViewDataSource protocols, the UITableView object in storyboard has no idea about it. We have to tell the UITableView object that ViewController is the delegate object for the data source.</p><p>Go back to Main storyboard. Select the table view. Press and hold the control key, drag from the table view to the View Controller object in the document outline view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gz60pPFO8YuE0Q9nlO7dhQ.png" /><figcaption><em>Figure 8–13. Connecting Table View with its Datasource and Delegate</em></figcaption></figure><p>Release both buttons. In the pop-over menu, select <em>dataSource</em>. Repeat the above steps and make a connection with <em>delegate</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQSmwfl5LSG89cozXOJ3ZA.png" /><figcaption><em>Figure 8–14. Selecting the dataSource and delegate outlets</em></figcaption></figure><p>That’s it. To ensure the connections are linked properly, you can select the table view again. Click the Connections Inspector icon in the Utility area to reveal the existing connections. Alternatively, you can right-click the table view to reveal the connections as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDdD4LyZWJ9AO-vuUOmVHg.png" /><figcaption><em>Figure 8–15. Two ways to reveal the connections</em></figcaption></figure><h3>Test Your App</h3><p>Finally, you’re ready to test your app. Simply hit the <em>Run</em> button and load your app in the simulator. Your app should now show a list of restaurant names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I0iQn3SwrZ0f5oDxCmsqQ.png" /><figcaption><em>Figure 8–16. SimpleTable App</em></figcaption></figure><pre>Quick tip: To scroll through the table in the iOS simulator, simply &amp; hold on the table, drag it up and down to move it.</pre><h3>Add Thumbnail to Table View</h3><p>Wouldn&#39;t it be great to add an image to each row? UITableView makes it extremely easy to do this. You just need to add a line of code to insert a thumbnail in each row.</p><p>First, download the sample images from</p><p><a href="https://drive.google.com/drive/folders/1br1lCj2WcKRxHsheXUN00WHhJhMmT2jA?usp=share_link">simpletable-images1 (1) - Google Drive</a></p><p>The zipped archive contains three image files. Unzip the file, and drag the images from Finder to the asset catalog (Assets.xcassets).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VanRa47F9i3zrY3_sWJdQ.png" /><figcaption><em>Figure 8–17. Adding images to the asset catalog</em></figcaption></figure><p>Now edit ViewController.swift and add the following line of code in the tableView(_:cellForRowAtIndexPath:) method. Put it right before return cell:</p><pre>cell.imageView?.image = UIImage(named: &quot;restaurant&quot;)</pre><p>After the changes, the method should look like this:</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>    let cellIdentifier = &quot;datacell&quot;<br>    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)<br><br>    // Configure the cell...<br>    cell.textLabel?.text = restaurantNames[indexPath.row]<br>    cell.imageView?.image = UIImage(named: &quot;restaurant&quot;)<br><br>    return cell<br>}</pre><p>The UIImage class provided by the UIKit framework lets you create images from files. It supports various image formats such as PNG, PDF and JPEG. You can pass the name of the image (file extension is optional) and the class will load the image from the asset catalog.</p><p>Earlier, we selected to use the Basic cell style for the table view cell. This type of cell style already comes with a default area for display images or thumbnails. This line of code instructs UITableView to load the image and display it in the image view of the table cell. Now, hit the &quot;Run&quot; button again and your SimpleTable app should display the image in each row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM059hOhkehaGBB4Ad7u_g.png" /><figcaption><em>Figure 8–18. SimpleTable app with images</em></figcaption></figure><h3>Hide the Status Bar</h3><p>The content of table view now overlaps with the status bar. This doesn’t look good. An easy remedy is to hide the status bar. You can control the appearance of the status bar on a per view controller basis. If you don’t want to show the status bar in a particular view controller, simply add the following lines of code before the last closing curly bracket (}):</p><pre>override var prefersStatusBarHidden: Bool {<br>    return true<br>}</pre><p>The prefersStatusBarHidden property indicates whether the view controller should hide the status bar. By default, the value is set to false. To hide the status, we have to override the default value and set it to true. Insert the code to the ViewController class and test the app again. You should have a full-screen table view without status bar.</p><h3>Exercise #1</h3><p>The demo app displays the same image for all table cells. Try to tweak the app such that it shows a different image in each cell (hint: Create another array for the images). You can download the image pack from</p><p><a href="https://drive.google.com/drive/folders/1oRlcDhBKmlwWReQJbL61aSaLgefK6nYn?usp=share_link">simpletable-images2 (2) - Google Drive</a></p><p>Figure 8–19 shows the resulting screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiSQGcwHC2ujmhwyYWyWaw.png" /><figcaption><em>Figure 8–19. Displaying different images in the demo app</em></figcaption></figure><pre>Quick note: In case you do not know how to complete the exercise, no worries. I will go through it with you in the next chapter or you can download the solution at the end of the chapter.</pre><pre>Credit: The images used in this demo project are provided by unsplash.com.</pre><h3>Summary</h3><p>Table view is one of the most commonly used elements in iOS programming. If you thoroughly understood the materials and built the app, you should have a good idea of how to create your own table view.</p><p>I tried to keep everything simple in the demo app. In a real world app, the table data is generally not &#39;hard-coded&#39;. Usually, it&#39;s loaded from a file, database or somewhere else. We&#39;ll talk about that later. Meanwhile, make sure you thoroughly understand how the table view works. Otherwise, go back to the beginning and study the chapter again.</p><p>For reference, you can download the complete Xcode project from</p><p><a href="https://drive.google.com/drive/folders/1OnHZUItTVYTtUR6kP9MS5IUhOlrzVQ7b?usp=share_link">SimpleTable - Google Drive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23dafe52f5f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4- Designing UI Using Stack Views using UIKit]]></title>
            <link>https://medium.com/@thanhtra.sqcb/4-designing-ui-using-stack-views-using-uikit-5242a2278e7b?source=rss-2337ce422add------2</link>
            <guid isPermaLink="false">https://medium.com/p/5242a2278e7b</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[NPSoftware]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 09:26:32 GMT</pubDate>
            <atom:updated>2023-03-02T09:26:32.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atX5QemMYYzO2mUFoPCncA.png" /></figure><p>I have given you a brief overview of auto layout. The examples that we have worked on were pretty easy. However, as your app UI becomes more complex, you will find it more difficult to define the layout constraints for all UI objects. Starting from iOS 9, Apple introduced a powerful feature called Stack Views that would make our developers’ life a little bit simpler. You no longer need to define auto layout constraints for every UI objects. Stack views will take care of most of that.</p><p>In this chapter, we will continue to focus on discussing UI design with Interface Builder. I will teach you how to build a more comprehensive UI, which you may come across in a real-world application. You will learn how to:</p><ol><li>Use stack views to lay out user interfaces.</li><li>Use image views to display images.</li><li>Manage images using the built-in asset catalog.</li><li>Adapt stack views using Size Classes.</li></ol><p>On top of the above, we will explore more about auto layout. You’ll be amazed how much you can get done without writing a line of code.</p><h3>What is a Stack View</h3><p>First things first, what is a stack view? The stack view provides a streamlined interface for laying out a collection of views in either a column or a row. In Keynote or Microsoft Powerpoint, you can group multiple objects together so that they can be moved or resized as a single object. Stack views offer a very similar feature. You can embed multiple UI objects into one by using stack views. In most cases, for views embedded in a stack view, you no longer need to define auto layout constraints.</p><pre>Quick note: For views embedded in a stack view, they are usually known as arranged views.</pre><p>The stack view manages the layout of its subviews and automatically applies layout constraints for you. That means the subviews are ready to adapt to different screen sizes. Furthermore, you can embed a stack view in another stack view to build more complex user interfaces. Sounds cool, right?</p><p>Don’t get me wrong. It doesn’t mean you do not need to deal with auto layout. You still need to define the layout constraints for the stack views. It just saves you time from creating constraints for every UI element and makes it super easy to add/remove views from the layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Ec0OvMDu8Aas4kN7J57zQ.png" /><figcaption><em>Figure 6–1. Horizontal Stack View (left) / Vertical Stack View (right)</em></figcaption></figure><p>Xcode provides two ways to use stack view:</p><ol><li>You can drag a Stack View (horizontal / vertical) from the Object library, and put it right into the storyboard. You then drag and drop view objects such as labels, buttons, image views into the stack view.</li><li>Alternatively, you can use the Stack option in the auto layout bar. For this approach, you select two or more view objects and then choose the Stack option. Interface Builder then embeds the objects into a stack view and resizes it automatically.</li></ol><p>If you still have no ideas about stack views, no worries. We’ll go through both approaches in this chapter. Just read on and you’ll understand what I mean in a minute.</p><h3>The Sample App</h3><p>Let’s first take a look at the demo app we’re going to build. I will show you how to lay out a welcome screen like this using stack views:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*211NpPiTH7Mewk9CUaqXAw.png" /><figcaption><em>Figure 6–2. The sample app</em></figcaption></figure><p>You can create the same UI without using stack views. But you will soon see how stack views completely change the way how you layout user interfaces. Again, there is no coding in this chapter. We will just focus on using Interface Builder to build an adaptive user interface. This is a crucial skill you will need in app development.</p><h3>Creating a New Project</h3><p>Now fire up Xcode and create a new Xcode project. Choose Application (under iOS) &gt; App and click “Next”. You can simply fill in the project options as follows:</p><ul><li><strong>Product Name: StackViewDemo</strong> — This is the name of your app.</li><li><strong>Team:</strong> Just leave it as it is.</li><li><strong>Organization Identifier: com.appcoda</strong> — It’s actually the domain name written the other way round. If you have a domain, you can use your own domain name. Otherwise, you may use “com.appcoda” or just fill in “edu.self”.</li><li><strong>Bundle Identifier: com.appcoda.StackViewDemo</strong> — It’s a unique identifier of your app, which is used during app submission. You do not need to fill in this option. Xcode automatically generates it for you.</li><li><strong>Interface: Storyboard</strong> — As explained before, Xcode now supports two ways to build UI. Please change the option to Storyboard because this book uses UIKit and Storyboard for UI development.</li><li><strong>Language: Swift</strong> — We’ll use Swift to develop the project.</li><li><strong>Use Core Data: [unchecked]</strong> — Do not select this option. You do not need Core Data for this simple project.</li><li><strong>Include Tests: [unchecked]</strong> — Do not select this option. You do not need any tests for this simple project.</li></ul><p>Click “Next” to continue. Xcode then asks you where to save the StackViewDemo project. Pick a folder on your Mac. Click “Create” to continue.</p><h3>Adding Images to the Xcode Project</h3><p>As you may notice, the sample app has three images. The question is how can you bundle images in Xcode projects?</p><p>In each Xcode project, it includes an asset catalog (i.e. Assets.xcassets) for managing images and icons that are used by your app. Go to the project navigator and select the Assets.xcassetsfolder. By default, it is empty with a blank Appicon set. We are not going to talk about app icons in this chapter, but will revisit it after building a real-world app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0JcnJ6HCeVwVelCstJ5Hw.png" /><figcaption><em>Figure 6–3. Asset Catalog</em></figcaption></figure><p>Now download this image set</p><p><a href="https://drive.google.com/drive/folders/1QkfNhxQ5ickyXwy9I10mpDZCJ2BWvKwX?usp=share_link">stackviewdemo-images (1) - Google Drive</a></p><p>and unzip it on your Mac. The zipped archive contains a total of 5 image files:</p><ul><li>user1.pdf</li><li>user2.png</li><li>user2@2x.png</li><li>user2@3x.png</li><li>user3.pdf</li></ul><pre>Credit: The images are provided by usersinsights.com.</pre><p>iOS supports two categories of images: <em>raster images</em> and <em>vector images</em>. Common image formats like PNG and JPEG are classified as raster images. Raster images use a grid of pixels to form a complete image. One problem of raster images is that it doesn’t scale up well. Increasing the size of a raster image usually means a significant loss of quality. This is why Apple recommends developers to provide three different resolutions of images when PNG is used. In this example, the image files comes with three versions. The one with @3x suffix, which has the highest resolution, is for iPhone 8 Plus, iPhone 13/14 Pro and Pro Max. The one with @2x suffix is for iPhone SE, iPhone 8, and iPhone 11, while the one without the @ suffix is for older devices with non-Retina display (e.g. iPad 2). For details about how the images are used, you can further refer to this link (<a href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/</a>).</p><p>Vector images usually have file types such as PDF and SVG. You can use tools like Sketch and Pixelmator to create vector images. Unlike raster images, vector images are comprised of paths instead of pixels. This allows the images to scale up without losing any image quality. Because of this feature, you just need to provide a single version of the image in PDF format for Xcode.</p><p>I intentionally include both image types in the example for illustration purpose. When developing a real world app, you usually work with either one or the other. So, which image type is more preferable? Whenever possible, ask your designer to prepare the images in PDF format. The overall file size is smaller and the images are scalable without losing quality.</p><p>To add the images to the asset catalog, all you need to do is drag the images from Finder, and drop them into the set list or set viewer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXasbMd-x9ncWYyyYQWd_w.png" /></figure><p>Once you add the images to the asset catalog, the set view automatically organizes the images into different wells. Later, to use the image, you just need to use the set name of a particular image (e.g. user1). You can omit the file extension. Even if you have multiple versions of the same image (e.g. user2), you don’t have to worry about which version (@2x/@3x) of the image to use. All these are handled by iOS accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99n3OorWRmugfXaSTAyrYA.png" /></figure><h3>Layout the Title Labels with Stack Views</h3><p>Now that you’ve bundled the necessary images in the project, let’s move onto the creation of stack views. First, open Main.storyboard. We&#39;ll start with the layout of these two labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8BXqTJdg5lCvIPi7p9fGA.png" /></figure><p>Stack view can arrange multiple views (known as arranged views) in both vertical and horizontal layouts. So first, you have to decide whether you want to use a vertical or horizontal stack view. The title and subtitle labels are arranged vertically. Therefore, vertical stack view is a suitable choice.</p><p>I used to lay out the UI on iPhone 14 Pro. Actually, you are free to use any device. However, to follow this chapter, I highly recommend you to design the user interface using iPhone 14 Pro. Please check the <em>View as</em> option in the configuration bar and make sure iPhone 14 Pro is used.</p><p>Now click the + button to display the Object library. Drag a Vertical Stack View object to the view controller in the storyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19Yng0yHM2eIuD322A4vZA.png" /></figure><p>Next, drag a label from the Object library and put it right into the stack view. Once you drop the label into the stack view, the stack view automatically embeds it and resizes itself to fit the label. Double click the label and change the title to “Instant Developer”. In the Attributes inspector, increase the font size to <em>40</em> points, and font style to <em>medium</em>. Optionally, you can change the color to <em>System Indigo Color</em> or whatever color you like.</p><p>Now, drag another label from the Object library to the stack view. As soon as you release the label, the stack view embeds the new label and arranges the two labels vertically like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRa-9O14hhMjz7xHImus6w.png" /></figure><p>Edit the title of the new label and change it to “Get help from experts in 15 minutes”. If you’ve done it correctly, the two labels should be placed inside the stack view. You can verify it by reviewing the objects in the document outline.</p><p>Currently, both labels are aligned to the left of the stack view. To change its alignment and appearance, you can modify the built-in properties of the stack view. Select the stack view and you can find its properties in the Attributes inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaDUuMMfaUnmG8yANv4_YQ.png" /><figcaption><em>Figure 6–9. Sample properties of a stack view</em></figcaption></figure><p>As a side note, if you have any problems selecting the stack view, you can hold the shift key and right-click the stack view. Interface Builder will then show you a shortcut menu for selection. Alternatively, you can select the stack view in the document outline. Both approaches would work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1Qk5netc8KY0qIUFlbz4w.png" /><figcaption><em>Figure 6–10. Shortcut menu for selection</em></figcaption></figure><p>Let’s briefly talk about each property of the stack view:</p><ul><li>The <em>axis</em> option indicates whether the arranged views should be layout vertically or horizontally. By changing it from vertical to horizontal, you can turn the existing stack view to a horizontal stack view.</li><li>The <em>alignment</em> option controls how the arranged views are aligned. For example, if it is set to Leading, the stack view aligns the leading edge (i.e. left) of its arranged views along its leading edge.</li><li>The <em>distribution</em> option defines the size and position of the arranged views. By default, it is set to <em>Fill</em>. In this case, the stack view tries its best to fit all subview in its available space. If it is set to <em>Fill Equally</em>, the vertical stack view distributes both labels equally so that they are all the same size along the vertical axis.</li></ul><p>Figure 6–11 shows some sample layouts of different properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rh_TyJDiaDtXHbtSsQxHug.png" /><figcaption><em>Figure 6–11. A quick demo of the stack view’s properties</em></figcaption></figure><p>For our demo app, we just need to change the <em>Alignment</em> option from <em>Fill</em> to <em>Center</em> and keep other options intact. This should center both labels.</p><p>Before moving onto the next section, make sure you position the stack view correctly. This would help you easier to follow the rest of the materials. You can select the stack view and go to the Size inspector. Ensure you set the value of X to 41 and Y to 70.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GBAHdYo_sxy0VwFjcW1oA.png" /><figcaption><em>Figure 6–12. Verify the position of the stack view</em></figcaption></figure><h3>Layout the Images Using the Stack Button</h3><p>At the very beginning of this tutorial, I mentioned that there are two ways to use stack views. Earlier, you added a stack view from the object library. Now I’d like to show you another approach.</p><p>We’re going to lay out the three user images. In iOS, we use image views to display images. From the Object library, look for the image view object, and drag it into the view. Once you added the image view, select the Attributes inspector. The image option already loads the available images from the asset catalog. Simply set it to user1. In the Size inspector, set the width of the image to 100 and height to 134.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYUcJcmdQ7j6vMWQYFyfpQ.png" /><figcaption><em>Figure 6–13. Adding an image view for displaying images</em></figcaption></figure><p>Repeat the procedures to add two more image views, and place them next to each other. Set the image of the second and third image view to user2 and user3 respectively. Your layout should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfyTIpMJdbhMoscuEU3Oig.png" /><figcaption><em>Figure 6–14. Assign the images to the image views</em></figcaption></figure><p>Using stack views minimizes the number of layout constraints you have to define, but it doesn’t mean you do not need to define any auto layout constraints. For the image views, we want each of them to keep its aspect ratio. Later, the size of these images varies depending on the screen size. We want them to retain their aspect ratio, no matter they are stretched or squeezed.</p><p>To do that, in the document outline view, control-drag horizontally on the image view of user1. In the shortcut menu, select Aspect Ratio. Repeat the same procedure for the other two image views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QS7iEiEtS6BXEI85lG9S5Q.png" /><figcaption><em>Figure 6–15. Adding an aspect ratio constraint</em></figcaption></figure><p>Now I want to group these three image views together using a stack view, so it is easier to manage. However, we will use an alternative approach to create the stack view.</p><p>Hold the command key and click the three image views to select them. Then click the <em>Embed in</em>button in the layout bar and choose <em>Stack View</em>. Interface Builder automatically embeds the image views in a horizontal stack view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Et3tHutdOTykwksyiuRTg.png" /><figcaption><em>Figure 6–16. Group the image views in a horizontal stack view</em></figcaption></figure><p>To add some spacing between the image views, select the stack view and set the spacing to 20.</p><p>Now you have two stack views: one for the labels, and the other for the image views. These two stack views can actually be combined together for easier management. One great thing about stack views is that you can nest multiple stack views together.</p><p>To do that, select both stack views in the document outline view. Then click the <em>Embed in</em> &gt; <em>Stack View</em> to embed both stack views in a vertical stack view. After that, make sure that the alignment of the new stack view is set to <em>Fill</em>. By setting the alignment property to <em>Fill</em>, this ensures the image views are resized automatically on larger screens. You will understand what I mean when we preview the UI on iPad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC_LcsGOjSXkrcjW4YZFqg.png" /><figcaption><em>Figure 6–17. Nested stack views</em></figcaption></figure><p>Cool, right? So far the UI looks good on iPhone 14 Pro. But if you preview the UI on other devices, it doesn’t look as expected. The reason is that we haven’t defined the layout constraints for the stack views.</p><h3>Adding Layout Constraints for the Stack View</h3><p>For the stack view, we will define the following layout constraints:</p><ul><li>Set a spacing constraint between itself and the top layout guide, such that it is 50 points away from the top anchor of the safe area layout guide.</li><li>Set a spacing constraint between the left side of the stack view and the leading anchor of the safe area, such that there is a space of 10 points between them.</li><li>Set a spacing constraint between the right side of the stack view and the trailing anchor of the safe area, such that there is a space of 10 points between them.</li></ul><p>Now click the <em>Add New Constraint</em> button in the layout bar. Set the space constraints of the top, left and right side to 50, 10 and 10 respectively. When the constraint is enabled, it is indicated by a solid red bar. Then click the &quot;Add 3 Constraints&quot; button to add the constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhHhg8O-tW3vnuwuFu8tDw.png" /><figcaption><em>Figure 6–18. Adding multiple constraints using the Pin button</em></figcaption></figure><p>Once you added the constraints, Interface Builder automatically re-positions the stack view to the correct position that conforms to your layout constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOJKQh-IcgJvIdlb7JUC-A.png" /><figcaption><em>Figure 6–19. The position of the stack view after adding the spacing constraints</em></figcaption></figure><p>Now try to preview the interface on other devices. They should look pretty good. However, you may notice an issue:</p><ul><li>The <em>Instant Developer</em> label is truncated for iPhone SE.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3a7lydABs9n-dkq6MN6jg.png" /><figcaption><em>Figure 6–20. Previewing the UI on iPhone SE</em></figcaption></figure><p>So how can we fix the issue?</p><p>It is quite obvious that we can decrease the font size of the label. Xcode provides an automatic way to adjust the font size on the fly. Now select the <em>Instant Developer</em> label, and go to the Attributes inspector. Set the <em>Autoshrink</em> option to <em>Minimum Font Size</em>, and the value to 20.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2bpxw0oMcqus-9UBTz7ug.png" /><figcaption><em>Figure 6–21. Changing the autoshrink option of the label</em></figcaption></figure><p>By doing so, you tell Xcode (or iOS) to determine the suitable font size for the label such that it can perfectly be displayed. Now choose iPhone SE in the configuration bar to test out the UI. The label should be fully displayed.</p><h3>Adding a Label Below the Images</h3><p>There is a label right below the images that we haven’t added yet. I intentionally left it out so that I can show you how easy you can add an object to an existing stack view.</p><p>Open the Object library, drag a label object to the stack view holding the other two stack views. You will see a blue line that indicates the position of the insertion point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7xpEogasB5hsenYtpWsTw.png" /><figcaption><em>Figure 6–22. Adding a new label to an existing stack view</em></figcaption></figure><p>Next, select the new label. Go to the Attributes inspector, set the text to the following:</p><p><em>Need help with coding problems? Register!</em></p><p>Also, change the text alignment option to center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gn07-PjBAIahSZDxkbhMzg.png" /><figcaption><em>Figure 6–23. Changing the text alignment option to center</em></figcaption></figure><p>Now the UI looks pretty good on all devices. As you can see, stack views save you from defining constraints for the new label. It just inherits the constraints that you have defined earlier.</p><h3>Layout the Buttons Using a Stack View</h3><p>We haven’t finished yet. Let’s continue to layout the two buttons at the bottom of the screen.</p><p>First, click the + button to open the object library and drag a button from the library to the view. Double click the button to name it “Sign up”. In the Attributes inspector, change the Style option to <em>Filled</em>. iOS 15 comes with a number of built-in button style. The <em>Filled</em> style allows you to quickly create a button with solid background and rounded corners.</p><p>By default, the background color is set to blue. You can change its background option to <em>System Indigo Color</em>. Also, edit the Font option, set its size to 20 points and style to bold.</p><p>To make the button a bit bigger, you can go to the Size inspector and change the Size option to <em>Large</em>. If you want to make it even bigger, you can customize it width and height to 200 and 50points respectively.</p><p>Next, let’s create the <em>Log In</em> button. However, instead of repeating all the procedures. You can select the <em>Sign Up</em> button and press command-D to make a duplicate. Then move the new button and place it under the <em>Sign Up</em> button. You can change the new button’s text to Log In. In the Attributes inspector, change its background color to <em>System Gray Color</em>. Your UI should now look like that shown in figure 6-24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ziv1KEefUWDJbRnuSkxmg.png" /><figcaption><em>Figure 6–24. Adding two buttons to the view</em></figcaption></figure><p>Again, you do not need to set the layout constraints for these buttons, just let the stack view do the magic for you. Hold the command key and select both buttons. Then click the <em>Embed in</em> &gt; <em>Stack View</em> in the layout bar to group them in a vertical stack view. Next, center the stack view horizontally. To add a space between the buttons, select the stack view. In the Attributes inspector, set the value of <em>spacing</em> to 10.</p><p>Similarly, we have to define layout constraints for this stack view so that it is positioned close to the bottom of the view. Here are the layout constraints we’re going to define:</p><ul><li>Center the stack view horizontally, with respect to the container view.</li><li>Set a spacing constraint so that there is a space between the stack view and the bottom anchor of the safe area.</li></ul><p>Select the stack view that you just created. Click the Align button in the layout bar. Check the <em>Horizontally in Container</em> option and click <em>Add 1 Constraint</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4WzYWj7EjwDrUlVMDPQrQ.png" /><figcaption><em>Figure 6–25. Adding a new constraint to center the stack view horizontally</em></figcaption></figure><p>Next, to add a spacing constraint, click the <em>Add New Constraints</em> button and set the value of the bottom side to 30. Make sure the bar is in solid red. Click <em>Add 1 Constraint</em> to add the constraint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CcYzvraOKRcWJVBQQes4w.png" /><figcaption><em>Figure 6–26. Adding a spacing constraint to the stack view</em></figcaption></figure><p>One thing you may notice is that the button is narrower than expected. As you embed the buttons in the stack view, they are resized to its intrinsic size. If you want to set the width to 200, you will need to add the size constraint to the stack view. In the document view, control-drag from the stack view to itself to bring up the context menu. Choose <em>Width</em> to add the width constraint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1lkXmUXxxM-0cpMPUrVuw.png" /><figcaption><em>Figure 6–27. Adding the width constraint using control-drag</em></figcaption></figure><p>Once you added the constraints, you should see the constraints in the document outline. Expand it to reveal the width constraint. Since we need to change the width to 200 points, select the width constraint and go to the Attributes inspector. Change the constant value to 200. The stack view now has a fixed width of 200 points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GySu4heD8UupDiaAtZrUJg.png" /><figcaption><em>Figure 6–28. Editing the width constraint and change it to 200</em></figcaption></figure><p>Both buttons should have a height of 50 points. As you may know, we need to add a height constraint for both of them. Xcode allows you to add the same constraints to multiple objects at the same time. In this case, you can hold the command key and select both buttons. Then click the <em>Add new constraints</em> button and set the height to 50. Once you confirm to add the constraint, Xcode applies the constraint to both items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gURkL2qXxnqxRuNYMYyR3w.png" /><figcaption><em>Figure 6–29. Adding the height constraints to both buttons</em></figcaption></figure><p>It’s time to test the app again. You can preview the UI in Interface Builder or run the project on different devices. Your UI should look great on all devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyxjYd9VGB4lhPG7wBx6Qw.png" /><figcaption><em>Figure 6–30. Previewing the UI on iPhone SE</em></figcaption></figure><p>Do you notice the message “Need help with coding problems? Register!” was truncated on iPhone SE (1st generation)? Try to fix it by yourself. If you don’t know how to resolve the issue, go back to the earlier section to find the solution.</p><h3>Adapting Stack Views Using Size Classes</h3><p>Now that you’ve already built a nice UI using stack views, have you tested the layout in landscape orientation? If you turn the iPhone (or iPad) simulator sideway, the UI in landscape orientation looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEQODVr1EXts8Qtf37ndqg.png" /><figcaption><em>Figure 6–31. The app UI in landscape orientation on iPhone 11 Pro (left) and iPad Pro 12.9-inch (right)</em></figcaption></figure><p>It still looks pretty good on iPad. But it looks a bit weird on iPhone. There are a couple of things I want to customize to make it look better:</p><ol><li>Move the whole stack view a little bit closer to the top edge of the view.</li><li>The images are too big and the middle one was overlapped with the buttons.</li></ol><p>Please keep in mind that all the changes above are applied to iPhones in landscape orientation only. How can you do that?</p><p>This leads to the UI design concept known as Adaptive Layout. With adaptive layout, your apps can adapt their UI to a particular device and device orientation.</p><p>To achieve adaptive layout, Apple introduced a concept called <em>Size Classes</em>. This is probably the most important aspect which makes adaptive layout possible. Size classes are an abstraction of how a device is categorized depending on its screen size and orientation. You can use both size classes and auto layout together to design adaptive user interfaces.</p><p>A size class identifies a relative amount of display space for both vertical (height) and horizontal (width) dimensions. There are two types of size classes: <em>regular</em> and <em>compact</em>. A regular size class denotes a large amount of screen space, while a compact size class denotes a smaller amount of screen space.</p><p>By describing each display dimension using a size class, this will result in four abstract devices: <em>Regular width-Regular Height</em>, <em>Regular width-Compact Height</em>, <em>Compact width-Regular Height</em> and <em>Compact width-Compact Height</em>.</p><p>The table below shows the iOS devices and their corresponding size classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU1SfA5AQVfEfVjpjJVBsg.png" /><figcaption><em>Figure 6–32. Size Classes</em></figcaption></figure><p>To characterize a display environment, you must specify both a horizontal size class and vertical size class. For instance, an iPad has a regular horizontal (width) size class and a regular vertical (height) size class. For our customization, we want to provide layout specializations for iPhones in landscape orientation. In other words, here are the two size classes we have to deal with:</p><ul><li>Compact width-Compact height</li><li>Regular width-Compact height</li></ul><p>With an understanding of size classes, now go back to the Main storyboard. In the configuration bar, click the <em>Orientation</em> button to rotate the device. Next, select the spacing constraint between the top anchor of the safe area and the top side of the stack view. In the Attributes inspector, click the + button next to the <em>Constant</em> option. Select <em>Any</em> Width, <em>Compact</em> height and <em>Any</em> Gamut, and then set the value of this size class to -40.</p><pre>Quick note: Here, any width means both compact and regular width.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIVXioLWSwnb2_cm_BjDwQ.png" /></figure><p>By doing so, the space between the stack view and top edge of the view will be decreased when the iPhone is turned sideway. Preview the UI in Interface Builder or run the project on various iOS devices to see the result. You should notice that the spacing constraint only reduces its value when the device is an iPhone and in landscape mode.</p><p>Now let’s see take a look at the second issue, and see how we can reduce the size of the images when iPhone is in landscape orientation.</p><p>You are not only allowed to provide customization for constraints. Xcode lets you specify the size-class-specific property for stack views. Select the root stack view, which is the one that holds other stack views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBCBeDAL6idslhQzk81BJw.png" /><figcaption><em>Figure 6–34. Adding a customization for the stack view</em></figcaption></figure><p>In the Attributes inspector, click + next to Alignment to add a customization. Choose <em>Any</em>width, <em>Compact</em> height and <em>Any</em> Gamut, then click <em>Add Variation</em>. This lets you provide a customization for the alignment. Set the <em>hC</em> field to <em>Center</em>. In landscape orientation (iPhone only), we will keep the alignment as <em>Center</em> so that the image will not resize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhevJKUuAdm7kFnr6GO1TQ.png" /><figcaption><em>Figure 6–35. After adding customization for alignment</em></figcaption></figure><p>It now looks better on iPhone landscape. But there is still an issue with the “Need help with coding problems? Register!” message. It is still covered by the buttons. To resolve the issue, let me show you another trick of using size classes.</p><p>Select the stack view which holds both <em>Sign Up</em> and <em>Log In</em> button. In the Attributes inspector, click the + button next to Axis. Choose <em>Any</em> width and <em>Compact</em> height, and click <em>Add Variation</em> to confirm. In the new hC field, set it to Horizontal. This means that both buttons should be arranged horizontally instead of vertically for iPhone landscape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0SUGk-OvW1MBw-nU0L3_w.png" /><figcaption><em>Figure 6–36. Adding layout specialization for the Axis option</em></figcaption></figure><p>Now part of the “Need help” message is still obscured by the buttons. There are a couple of constraints we have to tweak to make the UI look better. The width of the buttons’ stack view is limited to 200 points. Select the constraint and add another variation. Again, choose <em>Any</em> width and <em>Compact</em> height, and click <em>Add Variation</em> to add a specialization for the <em>Constant</em> option. In the new hC field, set its value to 300.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxCqNeKmvrCo4LEeiy_IPw.png" /><figcaption><em>Figure 6–37. Adding a customization for the width constraint</em></figcaption></figure><p>Once you made the change, both buttons are having the same size. It’s not done yet. Select the bottom spacing constraint of the stack view. Again, choose <em>Any</em> width and <em>Compact</em> height, and click <em>Add Variation</em> to add a specialization for the <em>Constant</em> option. In the new hC field, set its value to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHWh5TSGIPNjyJJPQVjWUA.png" /><figcaption><em>Figure 6–38. Adding a customization for the bottom space constraint</em></figcaption></figure><p>That’s it! You can run the app on different simulators again. The user interface will be adapted to fit different screen sizes and orientation.</p><h3>Preserving Vector Data</h3><p>Before I end this chapter, I want to show you a feature in Xcode known as <em>Preserve Vector Data</em>. I mentioned that we prefer to use vector images over raster images in iOS development because they can scale up or down without losing their quality. That’s partially true.</p><p>When a vector image is used, Xcode automatically converts it into static images (@1x, @2x @3x). It is pretty much like the user2 image we prepared, but the conversion is handled by Xcode. In this case, the image quality will still be slightly affected when the image is enlarged. If you try to run the demo on iPad Pro (12.9-inch), you should find that the image quality is not perfect.</p><p>Xcode comes with a feature called <em>Preserve Vector Data</em> that lets you preserve the vector data of the images. The option is disabled by default. To enable it, you can go to Assets.xcassets and choose one of the images. In the Attributes inspector, tick the <em>Preserve Vector Data</em> checkbox to enable the option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xyZ5fhHKUbpywOJk7ZlWw.png" /><figcaption><em>Figure 6–39. Enabled the Preserve Vector Data option</em></figcaption></figure><p>Now if you run the app on iPad Pro (12.9-inch) again, you will find the image looks much better. Figure 6–40 illustrates the image difference when the option is enabled or disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9j8hkOLNHaZt2uGqEPRm5g.png" /><figcaption><em>Figure 6–40. (left) with Preserve Vector Data disabled, (right) with Preserve Vector Data enabled</em></figcaption></figure><h3>Exercise #1</h3><p>To help you better understand how auto layout and size classes work, let’s have another simple exercise. You are required to update some constraints and create another layout specialization for iPhone (Portrait) and iPad. Here are the requirements:</p><ul><li>For all devices, change the width of the “Sign Up” and “Log in” buttons from 200 to 250 points.</li><li>For iPad, increase the font size of the “Instant Developer” label to 65 points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWtnDlkvR4V9sIH1HsP94w.png" /><figcaption><em>Figure 6–41. UI requirements for exercise #1</em></figcaption></figure><h3>Exercise #2</h3><p>If exercise #1 is too simple for you, exercise #2 is for you. Try to build a UI like the one shown in figure 6–42. You can download the required images from</p><p><a href="https://drive.google.com/drive/folders/1ulF3dQyxXUA7DDTKn_JcsDs9JnH1pDJO?usp=share_link">student-tutor (1) - Google Drive</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxH1FyKrLvOPIz1HKzAuPA.jpeg" /><figcaption><em>Figure 6–42. UI requirements for exercise #2</em></figcaption></figure><pre>Credit: The background image is provided by Luka Dadiani.</pre><h3>Exercise #3</h3><p>Here is one more exercise for you to practice what you learned. Try to build a UI like the one shown in figure 6-43. You can use any of your photos for building the user interface. There is one feature about the <em>Label</em> object that we haven&#39;t covered but you need to use it in the exercise. By default, a label is set to display text in a single line. If you need the label to display multiple lines of text, you need to change the value of the <em>Lines</em> option. Say, to display two lines of text, you can simply set it to 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOyLWpTSoQLaj2M8SygYww.png" /><figcaption><em>Figure 6–43. UI requirements for exercise #3</em></figcaption></figure><h3>Summary</h3><p>Congratulations! You have finished the chapter and learned how to build an adaptive UI using stack views and size classes.</p><p>Stack views streamline the way you build user interfaces on iOS, with very minimal constraints. One question you may have is: when should you use stack views? Apple’s engineers recommended developers to adopt stack views first, and then only when you need to actually use raw constraints. So throughout this book, we will design the user interfaces using stack views.</p><p>For reference, you can download the complete Xcode project from:</p><ul><li>Complete project and solution to exercise #1:</li></ul><p><a href="https://drive.google.com/drive/folders/19d3VXNIgDgUQLhG4HXWfcadvM3w0wUL9?usp=share_link">StackViewDemo - Google Drive</a></p><ul><li>Solution to the exercise #2:</li></ul><p><a href="https://drive.google.com/drive/folders/1sfJEsPTFgoeGIbXmDn2owX93YShV-PCi?usp=share_link">StackViewDemoExercise2 - Google Drive</a></p><ul><li>Solution to the exercise #3:</li></ul><p><a href="https://drive.google.com/drive/folders/1_MpoSGqECTWox5-E0bVqEmy5DoZp_WlH?usp=share_link">StackViewDemoExercise3 - Google Drive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5242a2278e7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>