实现tableview滚动到底部的功能
//获得底部的位置
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height-scrollView.bounds.height)
//设置scrollview显示的位置
scrollView.setContentOffset(bottomOffset, animated: true)
string与nsstring截取字符串的区别
//string
let str = "my string"
let startIndex = str.index(str.startIndex, offsetBy: 3)
let endIndex = str.index(str.startIndex, offsetBy: 7)
let subStr = str[startIndex...endIndex]//"stain"
//nsstring
let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 0, length: 3))
如何获得app的delegate
//AppDelegate继承自UIApplicationDelegate,所以需要向下转换一下
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//此时就可以获得AppDelegate的属性了
let window = appDelegate.window
如何更好的设置一个global的值,比如通知的名称,路径,UserDefaults的key等等
建议写一个全局的struct,在该结构体内部写上整个app需要的global的值
struct GlobalKey {
//通知的key
struct NotificationKey {
static let Welcome = Notification.Name("HelloKey")
}
//固定的路径
struct GlobalPath {
static let Documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
}
//服务器信息
struct ServerSetting {
static let ServerIP = "1.1.1.1"
static let ServerPort = 123
}
}
//使用
print(GlobalKey.NotificationKey.Welcome)//Name(_rawValue: HelloKey)
print(GlobalKey.ServerSetting.ServerIP)//1.1.1.1
print(GlobalKey.GlobalPath.Documents)//...
如何实现string与date之间的互相转换
/* 首先需要知道dateFormat中,各个字母所代表的含义
G 年代标志符
y 年
M 月
d 日
h 时 在上午或下午 (1~12)
H 时 在一天中 (0~23)
m 分
s 秒
S 毫秒
E 星期
D 一年中的第几天
F 一月中第几个星期几
w 一年中第几个星期
W 一月中第几个星期
a 上午 / 下午 标记符
k 时 在一天中 (1~24)
K 时 在上午或下午 (0~11)
z 时区
*/
//string->date
let dateString = "02-03-2017 10:22:30"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let date = dateFormatter.date(from: dateString)//"Mar 2, 2017, 10:22 AM"
//date->string
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyy HH:mm:ss"
let dateString = dateFormatter.string(from: date)//"02-05-2017 13:57:25"
如何在可变数组中插入新的元素
var array = ["a","b"]
//添加一个元素在末尾
array.append("c")
//添加一个新的数组在末尾
let new = ["c","d"]
array.append(contentsOf: new)
array += new
//指定位置插入单个元素
array.insert("e", at: 0)
//指定位置插入数组
array.insert(contentsOf: new, at: 0)
如何使用空合运算符(??)
//空合运算符的作用:如果可选值为nil,则返回运算符后方的值,否则返回可选值解包后的值
var str: String?
str ?? "1"//结果为"1"
str = "c"
str ?? "1"//结果为"c"
如何获得本地Bundle和网络图片
//////////////////获得本地bundle中的图片//////////////////////
if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image
}
////////////获得网络图片:方法一////////////////
//首先创建一个方法,用于从网络下载图片,以及下载结束后执行闭包
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
//执行上方创建的方法,以及实现闭包内容
func downloadImage(url: URL) {
print("Download Started")
getDataFromUrl(url: url) { (data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
self.imageView.image = UIImage(data: data)
}
}
}
//最后使用
if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
imageView.contentMode = .scaleAspectFit
downloadImage(url: checkedUrl)
}
//////////////方法二////////////////
//编写一个扩展,里面包含下载的方法
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
//使用
imageView.downloadedFrom(link: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
查看user defaults写入的plist信息
//写入了键值对:pwd-123456
UserDefaults.standard.set("123456", forKey: "pwd")
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
//通过遍历,可以打印出user defaults的全部内容,里面就可以看到新写入的键值对。
//可以通过这个方法查看是否写入成功。
print("(key)--(value)")
}
如何快速清除字符串前后无用的空格和换行
let string = " 这是内容!
"
let newString = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)//"这是内容!"
如何快速将一个数组顺序混淆打乱
//给mutablecollection扩展一个方法,该方法的必须要条件是Indices.Iterator.Element == Index
extension MutableCollection where Indices.Iterator.Element == Index {
//将集合的内容打乱混淆
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}
extension Sequence {
//返回一个打乱后的数组
func shuffled() -> [Iterator.Element] {
var result = Array(self)
result.shuffle()
return result
}
}
//使用
let x = [1, 2, 3].shuffled()
// x == [2, 3, 1]
let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffled()
// fiveStrings == ["20", "45", "70", "30", ...]
var numbers = [1, 2, 3, 4]
numbers.shuffle()
// numbers == [3, 2, 1, 4]