Raywenderlich-ios design mode part 1/2 "translation"

Source: Internet
Author: User

Original address :http://www.raywenderlich.com/86477/introducing-ios-design-patterns-in-swift-part-1

Update 04/22/2015:updated for Xcode 6.3 and Swift 1.2.

Update Note:this Tutorial is updated for IOS 8 and Swift by Vincent Ngo. Original Post by Tutorial team member Eli Ganem.

Only in the original version of Swift, I add OC version, because I do not know swift, so I write the OC code may be wrong, please forgive ************

Design patterns are a reusable solution to common problems in software design, a template that helps you write code that is easy to understand and reuse, and helps you write low-coupling code to make it easier to change the content of your code.

In this two-part tutorial, you will create a music library app that will showcase music albums and related information.

In the process of developing this app, you will be familiar with the most common cocoa design patterns:

    • Creational (creation type): Singleton (singleton mode)
    • Structural (structural type): MVC, Decorator (decorative mode), Adapter (adapter mode), facade (appearance mode).
    • Behavioral (behavioral): Observer (Viewer mode), Memento (Memo mode)

Don't mistake this article for a theory; you'll use most of the above design patterns in this app, and your app will end up like this:

Download starter project, unzip, open bluelibraryswift.xcodeproj in Xcode

This project has three key points:

1. There are two iboutlet connected to Viewcontroller, one is table view and the other is toolbar

2. Storyboard has three parts, has created a constraint for AutoLayout, the top part is the place where the album cover is displayed, the part under the cover is Table view, the album related information is displayed, the last part is toolbar, there are two buttons, As you can see from the diagram: One undo, one delete.

3. An HTTP client class (HTTPClient), the implementation of the class is written later by you.

Note: Do you know that when you create a new Xcode project, your code is already in design mode? Mvc,delegate,protocol,singleton-You got it straight.

Before you dive into the first design pattern, you need to create two classes to store and display the data

    • NEW: File\new\file ... (or press the shortcut key command+n). Select IOS > Cocoa Touch Class and click Next. The class name is written as album NSObject的子类 . Finally: Select the language for swift and click Next,create.
    • Open Album.swift and add the following properties.
1 //Swift2 3var title:string!4var artist:string!5var genre:string!6var coverurl:string!7var year:string!8 9 //objective-cTen  One@property (nonatomic,copy) NSString *title; A@property (nonatomic,copy) NSString *artist; -@property (nonatomic,copy) NSString *genre; -@property (nonatomic,copy) NSString *Coverurl; the@property (nonatomic,copy) NSString *year;

5 properties are created, and the album class will focus on these 5 properties in real time.

    • Next add the Album object initialization method
//SwiftInit (title:string, artist:string, genre:string, coverurl:string, year:string) {super.init () Self.title =title Self.artist=artist Self.genre=genre Self.coverurl=Coverurl self.year=Year }//objective-c//Album.h+ (Album *) Initwithtitle: (NSString *) title Artist: (NSString *) artist Genre: (NSString *) genre Coverurl: (NSString *) Coverurl Year: (NSString *) year; //ALBUM.M+ (Album *) Initwithtitle: (NSString *) title Artist: (NSString *) artist Genre: (NSString *) genre Coverurl: (NSString *) Coverurl Year: (NSString *) year{if(self =[Super Init]) {Self.title=title Self.artist=artist Self.genre=genre Self.coverurl=Coverurl self.year=Year }}
    • Overriding the Description method
//SwiftOverridevar description:string {return "title: \ (title)"+"artist: \ (artist)"+"Genre: \ (genre)"+"Coverurl: \ (coverurl)"+"Year : \ (year)"}//objective-c(NSString*) description{return[NSString stringWithFormat:@"title:%@,artist:%@,genre:%@,coverurl:%@,year:%@", Self.title,self.artist,self.genre,self.coverurl,self.year];}

The Description method returns the properties of the album object as a string.

    • Create a second class, set the class name to Albumview, and inherit from UIView
1 //Swift2 3 Privatevar coverimage:uiimageview!4 Privatevar indicator:uiactivityindicatorview!5 6 //objective-c7 //write to. m file8 9 @implementatin AlbumviewTen  One@property (nonatomic,weak) Uiimageview *Coverimage; A@property (nonatomic,weak) Uiactivityindicatorview *indicator; -  - @end

Coverimage is an album cover picture, and the second property is an activity indicator that tracks the cover load in real time

These two properties are set to private type because there is no need to know the existence of these two properties outside of the Albumview class, they are only used in the internal implementation function. Use this very important rule when you want to create a library or framework for everyone to use to keep private variable information out of the open.

    • Similarly, add an initialization method for the Albumview class
Required Init (coder Adecoder:nscoder) {super.init (Coder:adecoder) commoninit ()} init (Frame:cgrect, albumcover:s Tring) {super.init (frame:frame) Commoninit ()} func Commoninit () {backgroundcolor=Uicolor.blackcolor () coverimage= Uiimageview (Frame:cgrect (x:5Y:5, Width:frame.size.width-Ten, Height:frame.size.height-Ten) ) Addsubview (coverimage) indicator=Uiactivityindicatorview () indicator.center=Center Indicator.activityindicatorviewstyle= . Whitelarge indicator.startanimating () Addsubview (indicator)}//However, it is not known how OC should be written. 

Nscoder needs to be initialized because UIView complies with nscoding

Commoninit is an auxiliary method that is used in two init methods, which you will then need to set the default conditions for Albumview. Background black, sets the edge of 5 pixels for ImageView, and adds the Coverimage and indicator properties to the parent view.

    • Finally: Add the following methods
//Swiftfunc highlightalbum (#didHighlightView: Bool) {ifDidhighlightview = =true{backgroundcolor=uicolor.whitecolor ()}Else{backgroundcolor=Uicolor.blackcolor ()}} //OC- (void) Highlightalbum: (BOOL) didhighlightview{if([self didhighlightview]) {Self.view.coverImage.backgroundColor=[Uicolor Whitecolor]; }Else{Self.view.coverImage.backgroundColor=[Uicolor Blackcolor]; } }

The album cover is white when highlighted, and black on the contrary.

Compile the project, make sure everything is all fine, and then prepare to begin the first design pattern of learning.

King of Mvc–the King's design Patterns model

MVC is the cornerstone of cocoa, and there is no doubt that it is the most used design pattern. It categorizes objects by their regular role, and encourages developers to create catalogs for the code so that the project hierarchy is clear.

These three roles are:

    • Model (MODELS): Model objects store Application data and define methods for managing these data, just like your album class in this project.
    • View: The View object is responsible for visualizing the model and its interaction with the user, essentially all of the UIView derived objects, just like your ALBUMVIW class in this project.
    • Controller: Controllers object is the medium that coordinates the above work, it takes the model data and then presents it in the view, and listens to the interaction and manages the data according to it, now do you know who the controller is in your project? Yes, that's viewcontroller.

To achieve this design pattern, each object must be assigned to the Model,view,controller group.

You can describe the relationship of MVC:

When the model object's data changes, it notifies the Controller object, and the controller object updates the data displayed on the corresponding View object. When the user interacts with the View object, the View object notifies the controller object, and the controller object updates the data in the corresponding model object.

First update: 2016-03-02 11:58:18

Raywenderlich-ios design mode part 1/2 "translation"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.