所有小技巧都是基于Swift3
1.實現tableview滾動到底部的功能
//獲得底部的位置
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height-scrollView.bounds.height)
//設置scrollview顯示的位置
scrollView.setContentOffset(bottomOffset, animated: true)
2.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))
3.如何獲得app的delegate
//AppDelegate繼承自UIApplicationDelegate,所以需要向下轉換一下
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//此時就可以獲得AppDelegate的屬性了
let window = appDelegate.window
4.獲得app支持的語言
let languages = UserDefaults.standard.object(forKey: "AppleLanguages")
print(languages)//"en"
5.xcode8調試的時候,在控制臺輸出很多系統打印,如何取消
1.選擇edit scheme...
屏幕快照 2017-05-02 上午9.46.40.png
2.選中run,然后在environment variables中name輸入OS_ACTIVITY_MODE,value輸入disable即可
1
6.如何更好的設置一個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)//...
7.GCD如何實現回到主線程異步調用
DispatchQueue.main.async {
//code
}
8.如何忽略函數的返回值,而不產生警告
func conent() -> Int {
return 10
}
//用_代替返回值即可
_ = conent()
9.如何實現協議中,某些方法可選擇性的實現
//必須在協議前加上@objc
@objc protocol MyProtocol {
//該方法可以選擇性實現,前面必須加上@objc
@objc optional func doSomething()
}
class MyClass: MyProtocol {
//協議的方法可以不實現
}
10.如何實現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"
11.如何在可變數組中插入新的元素
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)
12.如何使用空合運算符(??)
//空合運算符的作用:如果可選值為nil,則返回運算符后方的值,否則返回可選值解包后的值
var str: String?
str ?? "1"http://結果為"1"
str = "c"
str ?? "1"http://結果為"c"
13.如何獲得本地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")
14.查看user defaults寫入的plist信息
//寫入了鍵值對:pwd-123456
UserDefaults.standard.set("123456", forKey: "pwd")
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
//通過遍歷,可以打印出user defaults的全部內容,里面就可以看到新寫入的鍵值對。
//可以通過這個方法查看是否寫入成功。
print("\(key)--\(value)")
}
15.如何快速清除字符串前后無用的空格和換行
let string = " \t\t 這是內容! \n \t \n "
let newString = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)//"這是內容!"
//CharacterSet.whitespacesAndNewlines表示的是空格和換行。可以根據自己的需要修改成其它的。
16.如何快速將一個數組順序混淆打亂
//給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]