Swift 3 收集的小知识点

1.条件判断区间

#pragma mark   ==============条件判断区间==============
let age = 19
if 18...25 ~= age {
    print("条件满足")
}
同
if age >= 18 && age <= 25 {
    print("条件满足")
}
同
if case 18...25 = age {
    print("条件满足")
}

2.多标志符字符串分割成数组

#pragma mark   ==============多标志符字符串分割==============
let text = "abc,vfr.yyuu"
let set = CharacterSet(charactersIn: ",.")
print(text.components(separatedBy: set)) 
// ["abc", "vfr", "yyuu"]

3.字符串是否为空

#pragma mark   ==============字符串是否为空==============
Non-Optional String
Check for zero length.

let myString: String = ""

if myString.isEmpty {
    print("String is empty.")
    return // or break, continue, throw
}

// myString is not empty (if this point is reached)
print(myString)

Optional String
Check for nil or zero length.
let myOptionalString: String? = nil

guard let myString = myOptionalString, !myString.isEmpty else {
    print("String is nil or empty.")
    return // or break, continue, throw
}

/// myString is neither nil nor empty (if this point is reached)
print(myString)

4.字符串是否包含空格

#pragma mark   ==============字符串是否包含空格==============
Here is how I check if string is blank. By 'blank' I mean a string that is either empty or contains only space/newline characters.
struct MyString {
  static func blank(text: String) -> Bool {
    let trimmed = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    return trimmed.isEmpty
  }
}
How to use:
MyString.blank(" ") // true

5.数组元素求和

#pragma mark   ==============可变参数累加,数组元素求和==============
func sum(input: Int...) -> Int {
            return input.reduce(0, +)
        }
print(sum(input: 1,2,3,4,5)) // 15

let arr: [Int] = [1, 2, 3]
print(arr.reduce(0, +))

// 字符串数组累加
let ss: [String] = ["hon", "zon", "-0"]
print(ss.reduce("", +))
// 输出:honzon-0

6.字符串是否包含数组中的元素

#pragma mark   ==============字符串是否包含数组中的元素==============
let words = ["Swift","iOS","cocoa","OSX","tvOS"]
let tweet = "This is an example tweet larking about Swift"
let valid = !words.filter ({ tweet.contains($0)}).isEmpty
或者
let valid2 = words.contains(where: tweet.contains)
print(valid)

7.导航栏返回图标

#pragma mark   ==============导航栏返回图标==============
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named:"find")
self.navigationController?.navigationBar.backIndicatorImage = UIImage(named:"find")

8.画虚线

#pragma mark   ==============画虚线==============
func drawDottedLine(lineView: UIView, offset: CGPoint) {
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = lineView.bounds
        shapeLayer.position = lineView.layer.position
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.lineWidth = 0.5
        shapeLayer.lineJoin = kCALineJoinRound
        // 4=线的宽度 1=每条线的间距
        shapeLayer.lineDashPattern = [NSNumber(value: 4), NSNumber(value: 1)]
        let path = CGMutablePath()
        
        path.move(to: CGPoint(x: offset.x, y: offset.y))
        path.addLine(to: CGPoint(x: lineView.frame.width - offset.x, y: offset.y))
        
        shapeLayer.path = path
        lineView.layer.addSublayer(shapeLayer)
    }

9.部分圆角图片

#pragma mark   ==============部分圆角图片==============
func cornerImage(frame: CGRect, image: UIImage, Radii: CGSize) -> UIImageView {
        let imageView = UIImageView(image: image)
        imageView.frame = frame
        let bezierPath = UIBezierPath(roundedRect: imageView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: Radii)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezierPath.cgPath
        imageView.layer.mask = shapeLayer
        return imageView
    }

10.修改状态栏背景颜色

#pragma mark   ==============修改状态栏背景颜色==============
func setStatusBarBackgroundColor(color: UIColor) {
        let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as? UIView
        guard  let statusBar = statusBarWindow?.value(forKey: "statusBar") as? UIView else {
            return
        }
        statusBar.backgroundColor = color
    }

11.UIImage加载

#pragma mark   ==============UIImage加载==============
UIImage(named: "imageName")// caching 
UIImage(contentsOfFile: "imageName")// no caching 
如果你要加载一个大图片而且是一次性使用,那么就没必要缓存这个图片,用contentsOfFile足矣,这样不会浪费内存来缓存它。
然而,在图片反复重用的情况下named是一个好得多的选择。

12.UIButton响应区域大小

#pragma mark   ==============UIButton响应区域44*44==============
extension UIButton {
    //处理button太小
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // if the button is hidden/disabled/transparent it can't be hit
        if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }
        // increase the hit frame to be at least as big as `minimumHitArea`
        let buttonSize = bounds.size
        let widthToAdd = max(44 - buttonSize.width, 0)

        let heightToAdd = max(44 - buttonSize.height, 0)
        let largerFrame = bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2)
        // perform hit test on larger frame
        return largerFrame.contains(point) ? self : nil
    }
}

13.忽略警告

pragma mark   ==============忽略警告==============
public extension Bool {
    // 默认情况下编译器就是会去检查返回参数是否有被使用,没有的话就会给出警告。如果你不想要这个警告,可以自己手动加上 @discardableResult
    @discardableResult public mutating func m_toggle() -> Bool {
        self = !self
        return self
    }
}

14.IBDesignable/IBInspectable 可视化xib/storyboard 属性设置

示例
// IBDesignable/IBInspectable,是iOS8的新特性。其主要功能是可以直接在XIB或者Storyboard中直接,设置UI类的属性。例如我们自定义一些控件,可以把控件的属性映射到XIB上
简单的说,就是自定义View的属性,可视化,在xib/Storyboard中可设置,主要用于复杂控件属性的设置
@IBDesignable
class RatingBar: UIView {
    @IBInspectable var  ratingMax: CGFloat = 10    //总分
    @IBInspectable var starNums: Int = 5        //星星总数
    //分数
    @IBInspectable var rating: CGFloat = 0 {
        didSet {
            if 0 > rating { rating = 0 }
            else if ratingMax < rating { rating = ratingMax }
            //回调给代理
            self.setNeedsLayout()
        }
    }
    
    @IBInspectable var imageLight: UIImage = UIImage(named: "ratingbar_star_light")!
    @IBInspectable var imageDark: UIImage = UIImage(named: "ratingbar_star_dark")!
    
    @IBInspectable var canAnimation: Bool = false    //是否开启动画模式
    @IBInspectable var animationTimeInterval: TimeInterval = 0.2 //动画时间
    @IBInspectable var isIndicator: Bool = false    //是否是一个指示器 (用户无法进行更改)
    
    private var foregroundRatingView: UIView!
    private var backgroundRatingView: UIView!
    
    private var isDrew = false    //是否创建过
    
    override init(frame: CGRect) {
        super.init(frame: frame)
       // self.buildView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
Swift 3 收集的小知识点_第1张图片
demo.png
/// 遍历删除subView
self.subviews.forEach({$0.removeFromSuperview()})
/// 打开设置界面
let urlObj = URL(string:UIApplicationOpenSettingsURLString)
if #available(iOS 10.0, *) {
      UIApplication.shared.open(urlObj! as URL, options: [ : ], completionHandler: { Success in

    })} else {
         UIApplication.shared.openURL(urlObj!)
     }
 }

15.颜色输入(即视功能)

Swift 3 收集的小知识点_第2张图片
color2.png
Swift 3 收集的小知识点_第3张图片
color.png

16.图片输入(即视功能)

  • 1.同颜色输入一样,代码直接输入image literal,左键双击缩略图标
Swift 3 收集的小知识点_第4张图片
image.png
  • 2.直接写图片名称
Swift 3 收集的小知识点_第5张图片
image2.png

原文链接

你可能感兴趣的:(Swift 3 收集的小知识点)