ios应用编程_第1部分-以编程方式创建iOS应用!

ios应用编程

IECSE速成课程:SWIFT开发 (IECSE CRASH COURSE: DEVELOPMENT WITH SWIFT)

This article is going to be the first article of this ten part series. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know.

本文将是该十部分系列的第一篇文章。 在完成10篇文章的过程中,我们将制作一个小型应用程序,该程序将显示一组将从网上获取的用户。 制作应用程序时,我们将介绍每个iOS开发人员必须知道的一些最重要的主题。

By the end of this article, you will have a clear idea about the basics of iOS and how we can start making iOS apps programmatically.

到本文结尾,您将对iOS的基础知识以及如何开始以编程方式开始制作iOS应用程序有一个清晰的了解。

First of all, let’s create an Xcode project by opening Xcode and selecting “Create a new Xcode project”.

首先,让我们通过打开Xcode并选择“ Create a new Xcode project ”来创建一个Xcode项目

Image for post
Select Single View App
选择单视图应用
Image for post
Give it a suitable name and save it anywhere
给它起一个合适的名称并保存在任何地方

Once our project has been created on Xcode, we will end up on a screen that looks like this.

在Xcode上创建我们的项目后,我们将最终看到一个类似以下的屏幕。

Image for post

为什么要以编程方式? (Why Programmatically?)

When we think about iOS development, there are two approaches to it:

当我们考虑iOS开发时,有两种方法:

  1. Using Storyboards: This is the more visual approach. This feature was introduced with iOS 5. In simple terms, what you do here is drag the various elements that make up the views that we want on our screen. It also helps us design transitions between the different views that we make.

    使用情节提要:这是更直观的方法。 iOS 5中引入了此功能。简单来说,您要做的就是拖动组成我们想要在屏幕上的视图的各种元素。 它还可以帮助我们设计我们在不同视图之间的过渡。

  2. Programmatically: This is the approach that we’ll be using. Here, we make our apps with nothing but code, we do not have any visual cues of the app without building it.

    编程方式:这是我们将要使用的方法。 在这里,我们只用代码来制作我们的应用程序,没有构建它就没有任何视觉提示。

I personally prefer a programmatic approach because it gives you better control over all the elements in your app. Anything that is achievable through a storyboard can be achieved through code. One of the other main advantages is the reusability of code. You can use one function to make your labels throughout your project. Also, when working with other developers, the storyboard approach may give merge conflicts, this problem is also taken care of in a programmatic approach.

我个人更喜欢编程方式,因为它可以让您更好地控制应用程序中的所有元素。 通过情节提要可以实现的任何事情都可以通过代码来实现。 其他主要优势之一是代码的可重用性。 您可以使用一个功能在整个项目中制作标签。 同样,当与其他开发人员一起工作时,情节提要方法可能会导致合并冲突,因此在程序化方法中也会解决此问题。

删除Mainstoryboard及其引用 (Removing Main.storyboard and its References)

Now, before we start with the coding part of it, we need to make a few changes so that our app doesn’t need a storyboard. So first, we will delete the reference to the storyboard “Main” from the general settings of our app.

现在,在开始进行编码部分之前,我们需要进行一些更改,以便我们的应用程序不需要情节提要。 因此,首先,我们将从应用程序的常规设置中删除对故事板“ Main”的引用。

Image for post
Make the highlighted textfield blank.
使突出显示的文本字段为空白。
Image for post
Move to Trash移至废纸”
Image for post
Delete the reference in info.plist (Select it and press cmd+delete)
删除info.plist中的引用(选择它并按cmd + delete)

Now that we’re done with these 3 steps, we’re ready to start coding.

既然我们完成了这三个步骤,就可以开始编码了。

创建表视图 (Creating the Table View)

可可粉 (Cocoa Touch)

Cocoa Touch is a name given to the collection of UI frameworks available as part of the iOS SDK. For us, CocoaTouch provides us with the implementation of most UI elements that we need. When we make a file for an element using CocoaTouch, we get some pre-written functions that we might need for implementing the respective element. We can change these functions and add new ones as and when we need them.

Cocoa Touch是为iOS SDK中提供的UI框架集合提供的名称。 对于我们来说,CocoaTouch为我们提供了所需的大多数UI元素的实现。 当我们使用CocoaTouch为元素创建文件时,我们获得了一些实现相应元素可能需要的预编写函数。 我们可以更改这些功能,并在需要时添加新功能。

First, let’s add a new file with Cocoa Touch Class.

首先,让我们使用Cocoa Touch Class添加一个新文件。

Image for post
Image for post
UITableViewController”. UITableViewController ”。

Let the Class be TableViewController for now, this will also become the name of the file that will get created.

现在让Class为TableViewController ,这也将成为将要创建的文件的名称。

Delete the “ViewController.swift” file, we won’t be using that.

删除“ ViewController.swift”文件,我们将不再使用它。

应用委托 (App Delegate)

The AppDelegate is one of the default classes that gets created by Xcode in any new project that we create. The App Delegate is considered to be the entry point of any app that we make. This class is also responsible for handling the application’s life cycle events, i.e., responding to the app being launched, backgrounded, foregrounded, receiving data and so on.

AppDelegate是Xcode在我们创建的任何新项目中创建的默认类之一。 应用程序代表被视为我们制作的任何应用程序的切入点 。 该类还负责处理应用程序的生命周期事件,即响应应用程序的启动,后台运行,前台运行,接收数据等。

Here, we need to create an instance of UIWindow which is a subclass of UIView. Every app has exactly one window. This window is created at launch time and is never destroyed or replaced. It is in this window that all our Controllers are contained.

在这里,我们需要创建UIWindow的实例,该实例是UIView的子类。 每个应用程序都只有一个窗口。 此窗口是在启动时创建的,永远不会销毁或替换。 在此窗口中包含我们所有的控制器。

Now we will set up the code in the AppDelegate.

现在,我们将在AppDelegate中设置代码。

Image for post

For now, we only need to make changes in application(_didFinishLaunchingWithOptions) in this class, the other functions remain the same.

现在,我们只需要在此类中的application(_didFinishLaunchingWithOptions)中进行更改,其他功能保持不变。

Now, let’s try to break down what is happening in these lines-

现在,让我们尝试分解这些行中发生的事情-

  • var window: UIWindow?, the question mark means it’s an optional type and that the value can be absent or present; this is similar to a nil value in other languages, but it works for all types not just classes.

    var window: UIWindow? ,问号表示它是可选类型,并且该值可以不存在或存在; 这类似于其他语言中的nil值,但它适用于所有类型,而不仅是类。

  • We will talk about the conditional if #available(iOS 13.0,*), when we take a look at the SceneDelegate.

    我们将讨论条件 if #available(iOS 13.0,*) ,当我们看一下SceneDelegate时。

  • window = UIWindow(…), this is done to create an instance of UIWindow, we name it window.

    window = UIWindow(…) ,这是为了创建UIWindow的实例,我们将其命名为window。

  • The rootViewController is the ViewController which is displayed as soon as our app is launched.

    rootViewController是ViewController,它会在我们的应用启动后立即显示。

  • window?.rootViewController = TableViewController(), this line sets up the rootViewController of our app to TableViewController(), ie this class which will contain our table.

    window?.rootViewController = TableViewController() ,此行将应用程序的rootViewController设置为TableViewController(),即将包含我们表的此类。

  • window?.makeKeyAndVisible(), this makes the window that we have created visible and makes it the key.

    window?.makeKeyAndVisible() ,这将使我们创建的窗口可见并使其成为键。

场景委托 (Scene Delegate)

When you consider the AppDelegate to be the object that’s responsible for your application’s life cycle, the SceneDelegate is responsible for what’s shown on the screen; the scenes or windows. It is the SceneDelegate’s scene(_:willConnectTo:options:), that creates our initial content view, creates a UIWindow, sets the window’s root view controller and makes the window key. As you can see, this is what we did for the devices that had older versions of iOS in the AppDelegate.

当您将AppDelegat e视为负责应用程序生命周期的对象时, SceneDelegate负责屏幕上显示的内容。 场景或窗户。 这是SceneDelegate的scene(_:willConnectTo:options:) ,它创建了我们的初始内容视图,创建了一个UIWindow,设置了窗口的根视图控制器并做出了窗口键。 如您所见,这就是我们对AppDelegate中具有旧版本iOS的设备所做的。

It was only since iOS 13, that the SceneDelegate class was introduced, before that all the tasks of the SceneDelegate used to be taken care of in the AppDelegate itself (this is exactly what we have done) but with iOS 13.0 SceneDelegate was introduced and all the work involving scenes is done in the SceneDelegate since then. If you want to read more about SceneDelegate, visit here.

只是从iOS 13开始,才引入了SceneDelegate类,之后,过去曾在AppDelegate本身中处理过SceneDelegate的所有任务(这正是我们所做的事情),但是在iOS 13.0中,引入了SceneDelegate,并且所有从那时起,涉及场景的工作在SceneDelegate中完成。 如果您想了解有关SceneDelegate的更多信息, 请访问此处

Now in the scene(_:willConnectTo:options:), we’ll add code similar to what we added in the AppDelegate.

现在在scene(_:willConnectTo:options:) ,我们将添加类似于在AppDelegate中添加的代码。

Image for post

guard let windowScene = (scene as ? UIWindowScene) else {return}, in this line of code we are making an instance of the WindowScene which we swill later embed in the window that we instantiate in the next line.

guard let windowScene = (scene as ? UIWindowScene) else {return} ,在此代码行中,我们将创建WindowScene的一个实例,稍后将其嵌入到在下一行实例化的窗口中。

Next, we set the window’s root view controller to TableViewController() and we declare the window as key and make it visible. Also, make an instance of AppDelegate and set it’s window to the instance of UIWindow we just created.

接下来,我们将窗口的根视图控制器设置为TableViewController(),然后将窗口声明为键并使其可见。 另外,创建一个AppDelegate实例,并将其窗口设置为我们刚创建的UIWindow实例。

Window can be thought of as a container in which scenes can be set.

可以将窗口视为可以设置场景的容器。

Now when you build the app, it should look like this

现在,当您构建应用程序时,它应如下所示

Image for post

In the next section, we will work on configuring the TableViewController.

在下一部分中,我们将配置TableViewController。

TableViewController (The TableViewController)

Any app consists of several views. Views are what we see on our screens. The table views are the views that help us in displaying lists of data in our applications, the class used for this is UITableViewController.

任何应用程序都包含多个视图。 视图是我们在屏幕上看到的。 表格视图是帮助我们在应用程序中显示数据列表的视图,用于此目的的类是UITableViewController。

UITableViewController is the subclass of UIViewController, it is a convenience class used to manage a table view. It aids in understanding some of the commonly used classes in iOS such as delegates and datasources.

UITableViewController是UIViewController的子类,它是用于管理表视图的便捷类。 它有助于理解iOS中一些常用的类,例如委托和数据源。

Coming to our TableViewController.swift, here is a function viewDidLoad(). This is the function that is called once our view has been loaded into the screen. It is also the function where most of our logic will go.

来到我们的TableViewController.swift ,这是一个函数viewDidLoad() 。 一旦我们的视图加载到屏幕中,就会调用此函数。 这也是我们大多数逻辑将执行的功能。

Now, we are going to initialise the TableViewController.

现在,我们将初始化TableViewController。

Image for post

Here, inside viewDidLoad() we first call, super.viewDidLoad(), as we already know now UITableViewController is a subclass of UIViewController. Even though here, the viewDidLoad() does not do anything, it is good practice to always call super on all the functions that you override because there might be some important initialisations taking place in these functions.

在这里,我们首先在viewDidLoad()内部调用super.viewDidLoad() ,我们现在已经知道UITableViewController是UIViewController的子类。 即使在这里,viewDidLoad()也不执行任何操作,还是一个好习惯,始终对您覆盖的所有函数调用super,因为这些函数中可能会发生一些重要的初始化。

Next, what we are doing is making a separate function to set up the TableView, this just helps us in keeping the code clean. Let’s take a deeper look into the function setUpTableView().

接下来,我们要做的是创建一个单独的函数来设置TableView,这仅有助于我们保持代码的清洁。 让我们更深入地研究一下setUpTableView()函数。

  • tableView.translatesAutoresizingMaskIntoConstraints = false, is the command that tells iOS that we are going to use AutoLayout, we’ll be looking at AutoLayout in detail in the next article, but we are going to give the relative positions of all the elements we’re going to be using and restrict iOS in generating Auto Layout constraints on its own. Especially when making UI programmatically, always make sure that you use this command.

    tableView.translatesAutoresizingMaskIntoConstraints = false ,它是告诉iOS我们将使用AutoLayout的命令,我们将在下一篇文章中详细介绍AutoLayout,但我们将给出所有元素的相对位置将要使用和限制iOS自行生成自动布局约束。 特别是在以编程方式制作UI时,请务必确保使用此命令。

  • Next, we need to inform the tableView about the type of cells that we will be using inside of it. That is that tableView.register(UITableViewCell.self,forCellReuseIdentifier: “Cell”) does, it registers the tableViewCells as the cells that we will be using in our tableView. we will get into details of the reuse identifier in detail in the next section.

    接下来,我们需要通知tableView有关将在其中使用的单元格类型。 那就是t ableView.register(UITableViewCell.self,forCellReuseIdentifier: “Cell”) 这样做,它将tableViewCells注册为我们将在tableView中使用的单元格。 我们将在下一部分中详细讨论重用标识符。

  • In the next two lines, we make the tableView conform to two protocol methods, what this means is that these give us a blueprint of how the data should be handled by the tableView.

    在接下来的两行中,我们使tableView符合两种协议方法,这意味着它们为我们提供了tableView应该如何处理数据的蓝图。
  • At last, we set up the height of each cell of the tableView and we make the tableView cells non-selectable and the last line removes the default lines that separate two cells.

    最后,我们设置tableView的每个单元格的高度,并使tableView单元格不可选择,最后一行删除分隔两个单元格的默认行。

In the next and the last section of the tutorial, now we just have to configure our cells.

在本教程的下一部分和最后一部分中,现在我们只需要配置单元。

设置单元 (Setting up the cells)

Let’s first add the final lines of our code and then try and understand what they do.

让我们首先添加代码的最后几行,然后尝试了解它们的作用。

Image for post

First, we change the function numberOfSections(..) to return 1, this, as the name suggests, is the number of sections our tableView will have. For now, we are going to keep it one. The function tableView(_numberOfRowsInSection section:Int), returns the number of cells that we want the section to have. (As we only have one section for now in our tableView).

首先,我们将函数numberOfSections(..)更改为返回1,顾名思义,这就是tableView将拥有的节数。 目前,我们将保留它一个。 函数tableView(_numberOfRowsInSection section:Int) ,返回我们希望该部分具有的单元格数。 (因为我们现在在tableView中只有一个部分)。

It is very important to understand the next function, tableView(_cellForRowAt indexPath:), this is where our cells are created and initialised.

了解下一个函数tableView(_cellForRowAt indexPath:)非常重要,这是创建和初始化单元格的地方。

可重复使用的细胞 (Reusable Cells)

Suppose our table had 10000 rows, in this case, if we made 10000 cells and we started scrolling towards the bottom of the table, eventually we would run out of memory and our app would crash. Hence what iOS does is, when a cell goes outside the view, i.e. the cell can no longer be seen, the same cell is used and the data inside it is changed accordingly and is again shown as a different cell. Hence, even if we have 10000 rows in our table, we can use very few cells to represent all the rows. This is because of the cells being reusable.

假设我们的表有10000行,在这种情况下,如果我们创建10000个单元格并开始向表底部滚动,最终我们将耗尽内存并导致应用崩溃。 因此,iOS要做的是,当一个单元格超出视图时,即不再可见该单元格时,将使用同一单元格,并且其内部的数据将相应更改,并再次显示为另一个单元格。 因此,即使表中有10000行,我们也可以使用很少的单元格来表示所有行。 这是因为单元可重复使用。

In the tableView that we made, where we registered the cells we were going to use, we also defined the forReusableIdentifier=”Cell”, now in the function tableView(_cellForRowAt indexPath:), we instantiate the cell with,let cell = tableView.dequeueReusableCell(withIdentifier:”Cell”,for: indexPath), here we need to make sure that the identifier we use is the same as what we registered in the tableView.

在我们制作的tableView中,我们注册了要使用的单元格的位置,我们还在函数中定义了forReusableIdentifier =“ Cell” tableView(_cellForRowAt indexPath:) 我们使用实例化单元格, let cell = tableView.dequeueReusableCell(withIdentifier:”Cell”,for: indexPath) 这里我们需要确保我们使用的标识符与我们在其中注册的标识符相同tableView。

索引路径 (IndexPath)

Index paths describe an item’s position inside a table view or collection view, storing both its section and its position inside that section. For example, the first row in a table would have section 0, row 0, whereas the eighth row in the fourth section would have section 3, row 7.

索引路径描述了项目在表视图或集合视图中的位置,同时存储了它的部分及其在该部分中的位置。 例如,表中的第一行将具有部分0,第0行,而第四部分的第八行将具有部分3,第7行。

Like for the code we have written, we store the row of the cell we are configuring in a variable t. Next, we use the ternary operator, this operator works with 3 values instead of 2. One of them is a check/conditional that is run, one is the value that is returned if the check is evaluated as true and one more value that is returned if the check is evaluated as false. For us, we check if t is odd, in which case we give the cell a color teal, otherwise the color returned is pink.

就像我们编写的代码一样,我们存储要在其中配置的单元格的行 变量t 。 接下来,我们使用三元运算符 ,该运算符使用3个值而不是2。其中一个是运行的检查/条件,一个是在检查被评估为true时返回的值,还有一个是如果支票被评估为假,则返回。 对于我们来说,我们检查t是否为奇数,在这种情况下,我们给单元格指定一个蓝绿色,否则返回的颜色是粉红色。

The final part is configuring the tableViewCell, which we will cover in the next tutorial about making a custom UITableViewCell.

最后一部分是配置tableViewCell,我们将在下一个教程中介绍如何制作自定义UITableViewCell。

The app that we have made until now looks like this.

到目前为止,我们制作的应用程序看起来像这样。

Image for post

结语 (Wrapping Up)

In this article, we’ve looked at how we can get started with making iOS apps programmatically. We’ve looked at some of the very important concepts including AppDelegate, SceneDelegate and we’ve set up our TableViewController so that we can use this going ahead.

在本文中,我们研究了如何开始以编程方式制作iOS应用。 我们研究了一些非常重要的概念,包括AppDelegate,SceneDelegate,并设置了TableViewController,以便我们可以继续使用它。

恭喜🎉! 您刚刚完成了第一个教程! (Congratulations🎉! You have just completed the first tutorial!)

All of the above-written code is available on Github. Watch this space for more interesting challenges, up next in this series!

所有上面编写的代码都可以在Github上找到 观看此空间,了解更多有趣的挑战,本系列中的下一个!

Confused about something? Let us know in the responses below. 😄

对某事感到困惑? 在下面的回复中告诉我们。 😄

翻译自: https://medium.com/iecse-hashtag/swift-part-1-creating-ios-apps-programmatically-fb32aa71fe34

ios应用编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值