所有小技巧都是基于Swift3
1.swift如何发送、接收、删除通知
//定义好通知的名称
let notificationName = Notification.Name("Notification")
override func viewDidLoad() {
super.viewDidLoad()
//添加通知接收
NotificationCenter.default.addObserver(self,
selector: #selector(method(notification:)),
name: notificationName,
object: nil)
//发送通知
NotificationCenter.default.post(name: notificationName,
object: nil)
//移除通知
NotificationCenter.default.removeObserver(self,
name: notificationName,
object: nil)//移除指定
NotificationCenter.default.removeObserver(self)//移除所有
}
func method(notification: Notification) {
print("接收到通知后执行")
}
//如果拥有该方法的类不是继承OC的类,那么该方法前需要加上@objc
@objc func method(notification: Notification) {
print("接收到通知后执行")
}
2.如何解决闭包内部的循环引用问题
//通过定义捕获列表解决
lazy var someClosure: Void -> String = {
//unowned:无主引用 weak:弱引用
[unowned self, weak delegate = self.delegate!] in
// 这里是闭包的函数体
}
3.如何获得某个变量的类型字符串
let string = "Hello"
let stringArray = ["one", "two"]
let dictionary = ["key": 2]
//打印具体内容
print(string)//Hello
print(stringArray)//["one", "two"]
print(dictionary)//["key": 2]
//打印类型
print(type(of: string))//"String"
print(type(of: stringArray))//Array<String>
print(type(of: dictionary))//Dictionary<String, Int>
//获得类型字符串
String(describing: type(of: string)) // "String"
String(describing: type(of: stringArray)) // "Array<String>"
String(describing: type(of: dictionary)) // "Dictionary<String, Int>"
//获得完整的类型字符串
String(reflecting: type(of: string)) // "Swift.String"
String(reflecting: type(of: stringArray)) // "Swift.Array<Swift.String>"
String(reflecting: type(of: dictionary)) // "Swift.Dictionary<Swift.String, Swift.Int>"
4.如何使用UIAlertController
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
let action1 = UIAlertAction(title: "确定",
style: .default) { (action) in
//点击确定后需要执行的操作写在这里
print("点击了确定")
}
let action2 = UIAlertAction(title: "取消",
style: .cancel) { (action) in
//点击取消后需要执行的操作写在这里
print("点击了取消")
}
alert.addAction(action1)
alert.addAction(action2)
self.present(alert,
animated: true) {
//这里可以进行一些操作
print("弹出后回调")
}
}
5.如何查找数组内部某个元素或者某些元素
class Person {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let p1 = Person(name: "a", age: 1)
let p2 = Person(name: "b", age: 2)
let p3 = Person(name: "c", age: 3)
let p4 = Person(name: "c", age: 31)
let array = [p1,p2,p3,p4]
//可以获得p1的下标为0
var result = array.index { $0 === p1 }
print(result!)
//通过元素内部的某个属性来查找index
result = array.index { $0.name == "c" }
print(result!)
//index只会返回第一个查找到的,查找多个,需要使用filter
let contents = array.filter { $0.name == "c" }
contents.count//contents会包含所有name=c的值
6.使用下标快速获得字符串指定位置的字符或者字符串
//给string扩展一些方法
extension String {
var length: Int { return self.characters.count }
//通过string[i]的方式获得指定位置字符
subscript (i: Int) -> String {
return self[Range(i ..< i+1)]
}
//通过string.substring(from: 3)方式获取
func substring(from: Int) -> String {
return self[Range(min(from, length) ..< length)]
}
//通过string.substring(to: 3)方式获取
func substring(to: Int) -> String {
return self[Range(0 ..< max(0, to))]
}
//通过string[1 ..< 3]的方式获取
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length,r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return self[Range(start ..< end)]
}
}
//使用
let str = "abcdef"
str[1 ..< 3] // returns "bc"
str[5] // returns "f"
str[80] // returns ""
str.substring(from: 3) // returns "def"
str.substring(to: str.length - 2) // returns "abcd"
7.生成指定位数的整数或者小数,不足位数以0补充
//指定位数字,不足的位数以0补充
extension Int {
func format(f: String) -> String {
return String(format: "%\(f)d", self)
}
}
//保留指定位小数,不足位数以0补充
extension Double {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
//使用
print(8.format(f: "06"))//000008
print(8.format(f: "02"))//08
print(9999.format(f: "02"))//9999
print(0.12345.format(f: ".2"))//0.12
print(0.1.format(f: ".4"))//0.1000
8.对数组内元素,按照指定属性指定规则进行排序
struct ImageFile {
var name: String
var ID: Int
}
let image1 = ImageFile(name: "a.jpg", ID: 3)
let image2 = ImageFile(name: "c.jpg", ID: 2)
let image3 = ImageFile(name: "b.jpg", ID: 1)
var images = [image1, image2, image3]
images.sort { $0.ID > $1.ID }//从大到小排序
images.sort { $0.name < $1.name }//从小到大排序
9.如何替换字符串中某个特定字符
let string = "This is my string"
//替换" "成"+",最终结果为:"This-is-my-string"
//方法一
let newString1 = string.replacingOccurrences(of: " ", with: "-")
//方法二
let toArray = string.components(separatedBy: " ")
let newString2 = toArray.joined(separator: "+")
//方法三
let newString3 = String(string.characters.map {
$0 == " " ? "+" : $0
})
10.如何发出http请求
let url = URL(string: "http://www.baidu.com")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
print(String(data: data!, encoding: .utf8))
}
task.resume()
11.如何修改imageview中image的颜色
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(frame: CGRect(x: 10, y: 100, width: 20, height: 20))
imageView.image = UIImage(named: "ADD")
changeTintColor(imageView: imageView, color: .red)
view.addSubview(imageView)
}
func changeTintColor(imageView: UIImageView, color: UIColor) {
imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
imageView.tintColor = color
}
效果: