1.控价相对于父控件居中:
点击Align按钮,选择Horizontally in Container 为水品居中,Vertically in Container为竖直居中
2.多个同级控件居中:
同时选中多个控件,点击Align按钮,选中Horizontal Centers相对于水平线居中,Vertical Centers竖直线居中,Baselines基线居中。
3.storyboard的controller和代码controller关联:
在storyboard中创建一个VC,新建一个swift文件导入UIKit继承UIViewController,点击VC顶部三个图标的最左边的,查看属性中的Custom Class选中创建的ViewController类即完成关联。
4.将SVC(Storyboard View Controller)中的控件关联到CVC(Code ViewController):
控件关联:点击两个环的按钮进入到代码和界面同时显示的方式,选中SVC中的控件按control键,拖动到代码区,在弹出框中填写名字connet即可
事件关联:选中控件,点击向右的箭头在下面Touch up Inside右侧的圆圈,拖到代码区域,填写名称connect即可。
关联失败处理:
关闭Xcode
shift+command+G弹出框,复制目录~/Library/Developer/XCode/DerivedData,进入后删除以项目名为开头的文件夹
打开Xcode即可
4.代码控制页面跳转
使用segue方式:选中源SVC中的控制器图标,右键拖动Show Detail到目标SVC就生成了一个segue,选中后点属性图标设置Identifier属性,在代码中调用self.performSegue(withIdentifier: "xxxx", sender: sender.self)
5.访问网络
//post
let parameters: Parameters = [
"email":"[email protected]",
"password":"123456"
]
Alamofire
.request("http://169.254.175.202:8888/user/user/login", method: .post , parameters: parameters)
.responseJSON {(dataResponse) in
if let json = dataResponse.result.value {
print("json: \(json)")
}
}
//get
Alamofire
.request("http://169.254.175.202:8888/user/user/[email protected]&password=123456")
.responseJSON {(dataResponse) in
if let json = dataResponse.result.value {
print("json: \(json)")
}
}
//获取String为
Alamofire
.request("http://169.254.200.61:8888/user/user/login", method: .post , parameters: parameters)
.responseString(completionHandler: {(response : DataResponse) in
switch response.result {
case .success(let value):
print("返回字符串:\(value)")
break
case .failure(let error):
print("error msg: \(error.localizedDescription)")
break
}
})
6.弹出对话框:
let alertView = UIAlertView();
alertView.title = "登陆信息";
alertView.message = "邮箱为:\(txtEmail.text!) 密码为:\(txtPassword.text!)";
alertView.addButton(withTitle: "OK");
alertView.show();
7.定义数据Model:
继承Codable,不要赋值
import UIKit
class User: Codable {
var id:Int64
var name:String
var email:String
var password:String
var loginState:Int
var machineNum:Int
var updateTime:Int64
}
8.导入第三方库:
新建Podfile文件:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target 'MiniLife-swift' do
pod 'Alamofire', '~> 4.7'
pod 'Moya', '~> 11.0'
end
安装配置文件中的库:
pod install
关闭xcode,点击xxx.xcworkspace打开xcode,发现已经引入pod
9.使用cocoaPods
//显示镜像地址
gem sources -l
//移除镜像地址
gem sources --remove https://rubygems.org/
//设置镜像地址
gem sources -a https://ruby.taobao.org/
//安装cocoapods
sudo gem install cocoapods
//查看库是否可用
pod search AFNetworking
//升级cocospods库
pod repo update
10.安装Ruby环境
//列出Ruby环境列表
rvm list known
//安装环境
rvm install 2.4.1
//把某个环境作为默认Ruby环境
rvm use 2.4.1 --default
11.JSON转Codable:
解析类型必须一一对应,否则识别不了,字段可为空要用Optional类型
//嵌套Codable
import Foundation
struct ResponseEntity: Codable {
struct User: Codable {
var id:Int64
var name:String
var email:String
var password:String
var loginState:Int!
var machineNum:String!
var updateTime:Int64!
}
var content: User
var code: Int
var msg: String
}
let jsonString = "{\"content\":{\"id\":1,\"name\":\"房德安\",\"email\":\"[email protected]\",\"password\":\"123456\",\"loginState\":0,\"machineNum\":\"0\",\"updateTime\":0},\"code\":1,\"msg\":\"登录成功\"}"
guard let jsonData = jsonString.data(using: .utf8) else {
print("JOSN字符串转JSON对象失败")
return
}
guard let obj = try? JSONDecoder().decode(ResponseEntity.self, from: jsonData) else {
print("JSON对象转Model失败")
return
}
print("msg:\(obj.msg)")
print("code:\(obj.code)")
print("name:\(obj.content.name)")
12.泛型模板类:可以使用泛型,字段页可以为空(要用!),类型不能错
//外层类
import Foundation
struct ResponseBean: Codable where T: Codable {
var content: T
var code: Int
var msg: String
}
//内层类
import Foundation
struct User: Codable {
var id:Int64
var name:String
var email:String
var password:String
var loginState:Int
var machineNum:String
var updateTime:Int64
}
13.最终Alamofire+JSON+Codable网络JSON解析为Model
Alamofire
.request("http://169.254.200.61:8888/user/user/login", method: .post , parameters: parameters)
.responseString(completionHandler: {(response : DataResponse) in
switch response.result {
case .success(let value):
print("返回字符串:\(value)")
guard let jsonData = value.data(using: .utf8) else {
print("JOSN字符串转JSON对象失败")
return
}
guard let obj = try? JSONDecoder().decode(ResponseBean.self, from: jsonData) else {
print("JSON对象转Model失败")
return
}
print("msg:\(obj.msg)")
print("code:\(obj.code)")
print("name:\(obj.content.name)")
break
case .failure(let error):
print("error msg: \(error.localizedDescription)")
break
}
})
14.数据库:Core Data
新建项目时选择Use Core Data,就会生成一个.xcdatamodeld的文件
打开次文件AddEntity,+ Attributes来添加表,右侧属性栏设置表名和Model名
不需要创建新的类,系统就会生成对应的Model类
使用先导入import CoreData
//1.增
//获取管理的数据上下文对象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//创建TUser对象
let tuser = NSEntityDescription.insertNewObject(forEntityName: "TUser", into: context) as! TUser
tuser.id = user.id
tuser.name = user.name
tuser.password = user.password
tuser.email = user.email
tuser.loginState = 1
tuser.machineNum = user.machineNum
tuser.updateTime = user.updateTime
do {
//保存
try context.save()
print("保存成功")
self.performSegue(withIdentifier: "login_to_main", sender: sender.self)
} catch {
print("保存失败")
}
//2.查
let email = "[email protected]"
let password = "123456"
//获取管理的数据上下文对象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//查询条件
let fetchRequest = NSFetchRequest(entityName: "TUser")
fetchRequest.fetchLimit = 1
fetchRequest.fetchOffset = 0
let predicate = NSPredicate(format: "email = %@ and password = %@ and loginState = 1", email,password)
fetchRequest.predicate = predicate
do {
let fetchedObjects = try context.fetch(fetchRequest)
//查出之后显示数据
if fetchedObjects.count > 0 {
let obj = fetchedObjects[0]
print("用户已登录")
print("name:\(obj.name!),\(obj.updateTime)")
} else {
print("用户未登录")
}
} catch {
print("查询失败")
}
//3.改
//查出之后
let fetchedObjects = try context.fetch(fetchRequest)
if fetchedObjects.count > 0 {
let obj = fetchedObjects[0]
obj.updateTime = 11111
try context.save()
} else {
print("用户未登录")
}
//4.删:查出之后
let fetchedObjects = try context.fetch(fetchRequest)
if fetchedObjects.count > 0 {
let obj = fetchedObjects[0]
context.delete(obj)
try context.save()
} else {
print("用户未登录")
}
15.使用三层泛型嵌套:
struct ResponseBean: Codable where T: Codable {
var content: T!
var code: Int
var msg: String
}
struct ResponseListBean: Codable where K: Codable {
var content:[K]!
var totalNum:Int64
var totalPage:Int64
var pageSize:Int64
}
struct Category: Codable {
var id:Int64!
var parentId:Int64!
var userId:Int64!
var name:String!
var orderNum:Int32!
var updateTime:Int64!
}
//转换
guard let obj = try? JSONDecoder().decode(ResponseBean>.self, from: jsonData) else {
print("JSON对象转Model失败")
return
}
16.使用Core Data的NSFetchRequest时,参数如果为数值型需要封装为NSNumber类型
let predicate = NSPredicate(format: "parentId = 0 and userId = %@", NSNumber(value: userId!))
17.页面跳转时传递数据:
在目标Controller中定义一个变量
在源Controller中实现prepare方法
当执行performSegue()方法之前会执行此方法
在目标Controller中直接使用赋值的变量
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination as! GoodsController
controller.parentId = parentClickId
}
18.代码segue返回:
self.presentingViewController?.dismiss(animated: true, completion: nil)
19.UILabel控件根据内容确定行数:Label属性的Lines设为0即可