Swift小知识点总结
1>判断输入字符串位数:
if phoneTextField.text?.lengthOfBytes(using: .utf8) != 11 {
self.showHint(hint: "请输入11位手机号码")
return
}
2>跳转设置WIfi页面:
/// 设置WIFi
fileprivate func setUpWiFi() {
guard let url = URL(string: "app-Prefs:root=WIFI") else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
3>
// MARK: - Date的扩展
/**
时间戳转化为字符串
time:时间戳字符串
*/
func timeStamp(timeStr: Double) -> String {
// let time = Double(timeStr)! + 28800 //因为时差问题要加8小时 == 28800 sec
// let time: TimeInterval = 1000
let detaildate = Date(timeIntervalSince1970: timeStr/1000.0)
//实例化一个NSDateFormatter对象
let dateFormatter = DateFormatter()
//设定时间格式,这里可以设置成自己需要的格式
dateFormatter.dateFormat = "yyyy-MM-dd HH:MM:ss"
let currentDateStr = dateFormatter.string(from: detaildate)
return currentDateStr
}
4>避免循环引用:
weak var weakSelf = self
let strongSelf = weakSelf
5>
类方法调用函数可以使用calss和static定义函数.
6>
Debug输出打印:
deinit {
debugPrint("SearchViewController--deinit")
}
7>修改搜索框的属性:
for view in searchBar.subviews {
for subView in view.subviews {
if NSStringFromClass(subView.classForCoder) == "UINavigationButton" {
let btn = subView as? UIButton
btn?.setTitle("取消" , for: .normal)
}
if NSStringFromClass(subView.classForCoder) == "UISearchBarTextField" {
let textField = subView as? UITextField
textField?.tintColor = UIColor.gray
}
}
}
8>去除字符串左右空格:
//去除搜索字符串左右和中间的空格
searchBar.text = searchBar.text!.trimmingCharacters(in: CharacterSet.whitespaces)
9>爱心动画:
@IBAction func like(_ sender: UIButton) {
//爱心大小
let heart = DMHeartFlyView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
//爱心的中心位置
heart.center = CGPoint(x: likeBtn.frame.origin.x, y: likeBtn.frame.origin.y)
view.addSubview(heart)
heart.animate(in: view)
//爱心按钮的 大小变化动画
let btnAnime = CAKeyframeAnimation(keyPath: "transform.scale")
btnAnime.values = [1.0, 0.7, 0.5, 0.3, 0.5, 0.7, 1.0, 1.2, 1.4, 1.2, 1.0]
btnAnime.keyTimes = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
btnAnime.duration = 0.2
sender.layer.add(btnAnime, forKey: "SHOW")
}