准备工作
在app store中下载Xcode(iOS应用程序的集成开发环境)
参考文档:Xcode Help
推荐书籍:《跟着项目学iOS应用开发:基于Swift 4》微信读书 该书实际上是根据Angela Yu在Udamy上的课程iOS & Swift - The Complete iOS App Development Bootcamp编写
查询问题:Stack Overflow;Apple API errors
-根据错误代码编号搜索
creat an App
creat a project
- 选模板:Single View App单视图应用程序相对简单灵活,更多功能可在后续开发过程中添加;
- 设置项目信息:
- Product name: 若使用特殊符号如空格,特殊符号在Bundle Identifier捆绑标识符(organization identifier followed by Product name)中以-出现,可使用驼峰命名法避免这个问题
- Organization Name: 个人开发者输入名字即可,如Li Ming
- Organization Identifier: com.example.followed by your organization name,如com.example.yuan
The organization identifier is a reverse DNS string that uniquely identifies your organization. If you don’t have a company identifier, use com.example.followed by your organization name, and replace it later. - - - Xcode Help > Get started > Creat a project > 4
- Use Core Data: 与数据存储相关,若不需要存储数据则不勾选
- Include Unit Test:
- Include UI Tests:
- Creat Git repository on my Mac: 是否需要对代码进行Source Control,管理代码的不同版本
Xcode界面
Navigation Pane 项目导航栏
Main.storyboard 用户界面文件:右击 > Open As / Source Code > Main.storyboard.xml (大部分时间在 Interface Builder 中可以完成用户界面工作)
Assets.cxassets:存放项目素材
设置面板
Project
General
Identify
- Bundle Identifier: 个人反向域名.ProjectName
Deployment Info
Device Orientation: Portrait(纵向Home在下方向)
Status Bar Style:Light Content
Targets
Signing
- Team: 如需应用在物理真机上则需要设定
Interface Builder
Object Library 对象库:Shift + Command + L
- Image View:只能呈现图像,不能交互
- Button
Debug Area 调试控制台
关闭控制台中系统日志的自动输出:Product/Scheme/Edit Scheme > Run/Arguments/Environment Variables > + Name:OS_ACTIVITY_MODE Value:disable > close
Utilities Pane
Attributes Inspector
View
Content Mode:
- Scale to Fill:拉伸图片使其充满容器
- Aspect Fit:保持长宽比使图片在容器内完整显现
- Aspect Fill 自动适应:保持图片长宽比充满容器
Tag:分辨出激活IBAction方法的到底是哪一个按钮
Size Inspector
Swift语言
class ViewController: UIViewController {
var randomDiceIndex: Int = 0
}
常用的数据类型
Int
整型包括正整数、负整数和0Float
单精度可精确到小数点后6位Double
双精度用于科学计算,可以存储64位的数字,精准到小数点后15位Bool
枚举值true
和false
String
字符串存储在双引号中- 数组:[, ] 元素同类型,索引从0开始,引用第一个元素
数组名[0]
- UIImage:通过UIImage的初始化方法加载Assets.xcassets中的图像
关键字
var
声明变量(存储数据的容器)
let
创建常量。常量所占用内存空间小于变量,建议尽量使用常量
循环
for number in arrayOdNumbers {}
for number in 1...10 where number % 2 == 0 {}
for number in 1..<10 {} //循环9次
if Immutable value ‘number’ was never used; consider replacing with ‘_’ or removing it. 常量
符号运算/其他
用反斜线+括号的方式在字符串中呈现常量或变量myName + "Liu" =" \(myName) Liu"
sum += number
等同于sum = sum + number
swift编译器会自动进行数据类型断言
面向对象的语言
类:声明变量
方法
类型转换:数据类型的初始化方法 数据类型()
rollButtonPressed (_sender: UIButton) {}
@IBAction func notePressed(_ sender: UIButton){ // notePresed方法中带有一个参数sender,它的类型是UIButton,代表当前用户与之发生交互的按钮
print(sender.tag) // 通过点(.)操作符访问sender对象的tag属性
}
函数
func 函数名(参数名: 参数值类型) -> 返回值类型{}
arc4random_uniform(x)
生成0~x-1的随机数,返回值类型为UInt32(无符号32位整数)
对象
代码库或框架
UIKit框架
UIKit (User Interface Kit) 用户界面工具:包含所有与用户界面、视图、视图控制器相关的类和函数API
Darwin.C.stdlib文件
arc4random_uniform
函数:基于C的UNIX函数
CocoaPods
CocoaPods类库管理工具
安装和设置CocoaPods
sudo gem install cocoapods # 将CocoaPods安装到系统中。gem即RubyGems,是一个用于对Ruby组件进行打包的Ruby打包系统;sudo命令代表以管理员权限执行后面的命令
pod setup --verbose # 设置。展示每一步设置进程和当前状态,设置完成后显示Setup completes
在Xcode项目中安装Pods
- 关闭Xcode(CocoaPods会在后台对Xcode进行一些改变)
- 生成并编辑Podfile文件
cd ThePathOfXcodeProject
pod init
open -a Xcode Podfile
- 安装开源库类
cd Project
pod --version # 检查CocoaPods版本
pod install
常见问题
errno 60:VPN设为Global Mode
443:Git默认设置HTTPS代理,Push应走SSH通道。解决方式:输入指令“git config --global --unset http.proxy”
- (若有)更新pod以更新开源库类
pod update
快捷键
command + / 注释
command + 单击:方法的详细信息
代码与界面元素的关联
step1 Show Assistant Editor 助手编辑器模式:
way 1: control+option+command+return
way 2: option + 单击ViewController.swift
way 3: 分页模式 > Navigation Pane > ViewController.swift
step 2 关联
(1)IBOutlet (Interface Builder Outlet)在某种情况下改变界面元素的外观
拖线操作:按住Control键,拖拽Object至代码对应位置
- Connection: Outlet
- Name: CamelCase
- Type: UIImageView
- Storage: Weak
@IBOutlet weak var nameExample: UIImageView! //指针变量nameExample,指向故事板中的Image View控件,变量类型同控件均是UIImageView。
(2)IBAction 在某种交互行为发生的时候通知程序代码
拖线操作way1:按住鼠标右键,并拖曳其到@IBAction func funcName (_ sender: UIButton) {}
方法上面
拖线操作way2:Utilities Pane > Connections Inspector > Sent Events > 动作如Touch Up Inside 右边的圆圈拖拽至 ViewController类中的方法上
- Connection: Action
- Name: CamelCase
- Type: UIButton
- Event: Touch Up Inside 单击 / Touch Drag Outside 拖拽
@IBOutlet func nameExample(_ sender: UIButton) {
} //指针变量nameExample,指向故事板中的Image View控件,变量类型同控件均是UIImageView。
调试
Terminating app due to uncaught exception ‘NSUnknownKeyException’ 未捕获到异常‘类中没有对应名称变量’导致程序终止运行
this class is not key value coding-compliant for the key… 一般是因在故事版中改变了某些关联导致
正确处理修改名称/删除某个IBOutlet或IBAction导致破坏界面和代码之间的关联关系:断开关联(右击界面元素删除关联),修改后重新建立连接
将应用安装到iPhone真机上
1 确保Xcode的版本与iPhone上系统的版本一致:通常高版本的Xcode可以兼容低版本的iOS,但是强烈建议两个版本保持一致。(⚠️“App” Is Not Available)
- Apple Store shows what version of Xcode supports what version of iOS.
- Document Outline: Targets > General > Deployment Info > the version of iOS that supported
2 Document Outline: Targets > “AppName” > Signing > Check Automatically manage signing & Team is your AppleID (Personal Team)
3 用数据线连接iPhone真机和Mac,确定其间相互信任
4 Product > Destination > iOS Device > “Your iPhone”
5 Product > Run > Password > Allow > “Could not launch YourApp”
6 Your iPhone > Settings > General > Device Management > Trust app from this developer
creat a playground
Playground:实时执行代码,立即显示结果,拥有交互功能。帮助开发者以最简单的方式实现各种想法的测试。
Creat a new playground: File/new/playground/iOS/Blank
Xcode playground 基础知识:运行代码
路径:editor -> Run/Stop Playground (to Current Line)
shortcuts: shift + command + enter (shift +enter)
左下角运行图标:Execute/Stop playground
长按:Automatically/Manually Run
常见问题
The Maximum Number of Provisioning Profiles Reached 应用程序已达到免费开发配置文件的最大数量
Apple将可在iPhone设备上加载的应用数量限制在每周10个
解决方案
1 创建新的AppleID,将账号添加至Xcode
2 删除应用程序:USB连接iPhone和Mac;Xcode/xxxProject/Window/Devices and Simulators/-
value of optional type ‘URL?’ must be unwrapped to a value of type ‘URL’ 必须将可选类型为“URL”的值展开为类型为“URL”的值
Coalesce using ‘??’ to provide a default when the optional value contains ‘nil’ 当可选值包含空值时,使用“??”合并以提供默认值
Force-unwrap using ‘!’ to abort execution if the optional value contains ‘nil’ 使用“!”强制展开如果可选值包含空值,则中止执行
cannot assign to property 无法分配属性
‘+=’ is not a prefix unary operator 不是前缀一元操作符
Left side of mutating operator isn’t mutable 可变运算符左侧不可变
优雅的写代码
DRY
Don’t Repeat Yourself
项目代码
Dicee
import UIKit
class ViewController: UIViewController {
var randomDiceIndex1: Int = 0 //声明变量存储随机数
var randomDiceIndex2: Int = 0
let diceArray = ["dice1","dice2","dice3","dice4","dice5","dice6"] //创建数组
@IBOutlet weak var diceImageView1: UIImageView! //关联界面与代码(外观)
@IBOutlet weak var diceImageView2: UIImageView! //指针变量diceImageView指向storyboard中的Image View控件,变量类型同界面空间元素均是UIImageView
func updateDiceImages() { // 更新骰子的面
randomDiceIndex1 = Int(arc4random_uniform(6))
randomDiceIndex2 = Int(arc4random_uniform(6))
diceImageView1.image = UIImage(named: diceArray[randomDiceIndex1]) // UIImage加载Assets.xcassets中的图像
diceImageView2.image = UIImage(named: diceArray[randomDiceIndex2]) // 通过数组改变指针变量指向对象的显示方式
}
override func viewDidLoad() { // 第一眼看见的骰子面是随机的
super.viewDidLoad()
updateDiceImages()
}
@IBAction func rollButtonPresses(_ sender: UIButton) { updateDiceImages()
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
updateDiceImages()
}
}
API
应用程序编程接口(Application Program Interface)
OpenWeather:注册需要科学上网收到人际验证码,通过注册后获得的API Key获取指定城市的气象信息。当应用程序在每分钟有超过60次APP_ID访问的时候会收取费用。