Swift 小知识点记录

字符串截取

let subString = (infoString as NSString).substring(with: NSRange(location: infoString.count-3, length: 3))
infoString = (infoString as NSString).substring(to: infoString.count-3)

Swift 中设置指定的圆角

//MARK: 添加圆角
// 因为涉及到layoutIfNeeded,所以使用的时候,必须在父视图 addsubview 添加了 sourceView 之后再做这个操作
/// 添加圆角,cornerPosition可以穿一个数组的组合来指定圆角 [UIRectCorner.bottomLeft, UIRectCorner.topRight],
func viewClipRoundCorner(from sourceView: UIView, cornerPosition: UIRectCorner, corner: CGFloat) {
    sourceView.layoutIfNeeded()
    let maskPath = UIBezierPath.init(roundedRect: sourceView.bounds,
                                     byRoundingCorners: cornerPosition,
                                     cornerRadii: CGSize(width: corner, height: corner))
    
    let maskLayer = CAShapeLayer()
    maskLayer.frame = sourceView.bounds
    maskLayer.path = maskPath.cgPath
    sourceView.layer.mask = maskLayer
}

富文本赋值

OC类似,富文本要传入一个字典,这里举的例子是往一个 Button 中设置他的title 为富文本

let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font : UIFont.init(name: "PingFangSC-Regular", size: 13)!,
                                                         NSAttributedStringKey.foregroundColor : UIColor.init(hexString: "#999999")!]
let loginBtnTitle = NSAttributedString(string: myLocal("drawer_loginOrRegister_button"), attributes: attributes)

数组截取

recentGameInfoArray: [FullGameInfo]
tempArray = Array(recentGameInfoArray[0...3])

计算 String 所占的宽度

//MARK: 计算字符锁占的宽度
func calculateStringWidth(srcString: String?, fontSize: CGFloat) -> CGFloat {
    guard let _ = srcString else { return 0 }
    
    let size:CGSize = CGSize.init(width: CGFloat(MAXFLOAT) , height: CGFloat(MAXFLOAT))
    let rec:CGRect = srcString!.boundingRect(with: size, options: NSStringDrawingOptions.usesFontLeading, attributes: [kCTFontAttributeName as NSAttributedStringKey : UIFont.systemFont(ofSize: fontSize)], context:nil);
    return rec.width
}

使用 present viewcontroller的问题

  • 问题描述: 方法进行界面跳转的时候,有时候会出现延迟,这个延迟有时候会有好几秒的时间才会执行 completion,有时候干脆就一直不会跳转。
  • 参考链接: iOS presentViewController:animated:completion:延迟问题

解决办法其实就是把present加到主线程中去

DispatchQueue.main.async {
  UIApplication.shared.keyWindow?.rootViewController?.present(alertSheet, animated: true, completion: nil)
}

闭包需要使用 weak self 的情况

为什么? 只要是稍微了解一点循环引用的人都知道,发生这种情况的主要原因是self持有了closure,而closure有持有了self,所以就造成了循环引用,从而小明对象没有被释放。

UITextField 切换可见性问题

效果.png

在UITextField输入密码后点击可见会发现光标往后移了一位即输入的内容多出一个空格.

textField.text = ""
textField.isSecureTextEntry = !passwordVisible

textField.text = tempText //切换可见性后,将原来的值赋回去

你可能感兴趣的:(Swift 小知识点记录)