Swift常用方法總結 不定期更新

搶手的哥發表於2017-12-14

1.本地讀取json檔案

	func readJsonFileByFileName(fileName : String) -> Any? {
        
        let path    = Bundle.main.path(forResource: "\(fileName).json", ofType: nil)
        let data    = NSData(contentsOfFile: path!)
        let jsonStr = try? JSONSerialization.jsonObject(with: data! as Data, options:.allowFragments)
        return jsonStr
    }
複製程式碼

2.實現手機號銀行卡號輸入加空格

eg:188 8888 8888


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let oldStr = textField.text
        var newStr = (oldStr as NSString?)?.replacingCharacters(in: range, with: string)
        if textField.placeholder == "請輸入銀行預留手機號" {
            
            newStr = newStr?.replacingOccurrences(of: " ", with: "")
            
            let expression = "^([1]{1}([34578]{1}([0-9]{0,9}+)?)?)?$"
            let regex = try?NSRegularExpression.init(pattern: expression, options: .caseInsensitive)
            let numOfMatches = regex?.matches(in: newStr!, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, (newStr?.characters.count)!))
            
            if numOfMatches?.count == 0 {
                
                return false
            }
            
            _ = self.formatPhoneNumText(textField: textField, range: range, string: string)
            
            return false
        }
        else if textField.placeholder == "請輸入銀行卡號"{
        
            
            // 只能輸入數字
            let characterSet = NSCharacterSet.init(charactersIn: "0123456789")
            
            let tempString = string.replacingOccurrences(of: " ", with: "")
            if (tempString.rangeOfCharacter(from: characterSet.inverted) != nil) {
                
                return false
            }
            
            var text = ((oldStr as NSString?)?.replacingCharacters(in: range, with: string))!
            text = text.replacingOccurrences(of: " ", with: "")
            
            var newString = ""
            
            while (text.characters.count) > 0 {
                
                let subString = (text as NSString).substring(to: min(text.characters.count, 4))
                newString = newString.appending(subString)
                if subString.characters.count == 4 {
                    
                    newString = newString.appending(" ")
                }
                text = (text as NSString).substring(from: min(text.characters.count, 4))
            }
            newString = newString.trimmingCharacters(in: characterSet.inverted)
            
            if newString.characters.count >= 24 {
                
                return false
            }
            
            if range.location != textField.text?.characters.count {
                
                textField.text = newString
                
                return false
            }
            
            textField.text = newString
            
         
            return false
            
            
            
        }else {
            // 只能輸入數字
            let characterSet = NSCharacterSet.init(charactersIn: "0123456789")
            
            let tempString = string.replacingOccurrences(of: " ", with: "")
            if (tempString.rangeOfCharacter(from: characterSet.inverted) != nil) {
                
                return false
            }
            if (newStr?.characters.count)! > 20 {
                
                return false
            }
        }
        
        return true
    }

private func formatPhoneNumText (textField:UITextField, range:NSRange, string:String) -> Bool {
        
        var text = textField.text!
        
        // 只能輸入數字
        let characterSet = NSCharacterSet.init(charactersIn: "0123456789")
        
        let tempString = string.replacingOccurrences(of: " ", with: "")
        if (tempString.rangeOfCharacter(from: characterSet.inverted) != nil) {
            
            return false
        }
        
        text = ((text as NSString?)?.replacingCharacters(in: range, with: string))!
        text = text.replacingOccurrences(of: " ", with: "")
        
        text.insert(" ", at: (text.startIndex))
        var newString = ""
        
        while (text.characters.count) > 0 {
            
            let subString = (text as NSString).substring(to: min(text.characters.count, 4))
            newString = newString.appending(subString)
            if subString.characters.count == 4 {
                
                newString = newString.appending(" ")
            }
            text = (text as NSString).substring(from: min(text.characters.count, 4))
        }
        newString = newString.trimmingCharacters(in: characterSet.inverted)
        
        if newString.characters.count >= 14 {
            
            return false
        }
        
        
        if range.location != textField.text?.characters.count {
            
            textField.text = newString
            
            if textField == self.phoneTextField {
                
            }
            
            return false
        }
        
        textField.text = newString
        
        if textField == self.phoneTextField {
            
        }
        return false
    }

複製程式碼

3.給UITextField的placeholder設定字型大小

使用:textField.verticalLeftPlaceholder(phFontSize: 15)

原始碼:
extension UITextField {
    
    func verticalLeftPlaceholder(phFontSize size: CGFloat = 15, text: String = "")  {
        
        var placeholderStr = text
        
        if text.isEmpty {
            
            placeholderStr = self.placeholder ?? ""
        }
        
        let pStyle = NSMutableParagraphStyle()
        pStyle.minimumLineHeight    = (self.font?.lineHeight)! - ((self.font?.lineHeight)! - UIFont.systemFont(ofSize: size).lineHeight)/2.0
        let aString = NSAttributedString(string: placeholderStr, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: size), NSParagraphStyleAttributeName: pStyle])
        
        self.attributedPlaceholder    = aString
    }
    
}
複製程式碼

4.插入排序

⒈ 從第一個元素開始,該元素可以認為已經被排序 ⒉ 取出下一個元素,在已經排序的元素序列中從後向前掃描 ⒊ 如果該元素(已排序)大於新元素,將該元素移到下一位置 ⒋ 重複步驟3,直到找到已排序的元素小於或者等於新元素的位置 ⒌ 將新元素插入到下一位置中 ⒍ 重複步驟2~5

public func insertionSort(arr: inout Array<Int>) {

    for i in 0..<arr.count - 1 {
        if arr[i + 1] < arr[i] {
            let temp = arr[i + 1]
            for j in (1...(i + 1)).reversed() {
                if arr[j - 1] > temp {
                    (arr[j - 1],arr[j]) = (arr[j],arr[j - 1])
                }
            }
        }
    }
}
複製程式碼

5.氣泡排序

⒈比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。 ⒉ 對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。 ⒊ 針對所有的元素重複以上的步驟,除了最後一個。 ⒋ 持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。

public func bubbleSort(arr: inout Array<Int>) {
    for i in 0..<(arr.count - 1) {
        for j in 0..<(arr.count - i - 1) {
            if arr[j] > arr[j + 1] {
                (arr[j],arr[j + 1]) = (arr[j + 1],arr[j])
            }
        }
    }
}
複製程式碼

6.快速排序(氣泡排序的改進版)

⒈設定兩個變數i、j,排序開始的時候:i=0,j=n-1。 ⒉ 以第一個陣列元素作為關鍵資料,賦值給key,即key=A[0]。 ⒊ 從j開始向前搜尋,即由後開始向前搜尋(j--),找到第一個小於key的值A[j],將A[j]和A[i]互換。 ⒋ 從i開始向後搜尋,即由前開始向後搜尋(i++),找到第一個大於key的A[i],將A[i]和A[j]互換。 ⒌重複第3、4步,直到i=j

 public func quickSort(arr: inout Array<Int>, leftIndex:  Int, rightIndex:  Int) {

    if leftIndex < rightIndex {
        var left = leftIndex
        var right = rightIndex
        let midIndex = getMidIndex(arr: &mArray, leftIndex: &left, rightIndex: &right)
        quickSort(arr: &mArray, leftIndex: leftIndex, rightIndex: midIndex - 1)
        quickSort(arr: &mArray, leftIndex: midIndex + 1, rightIndex: rightIndex)
    }
}

private func getMidIndex(arr: inout Array<Int>, leftIndex: inout Int, rightIndex: inout Int) -> (Int) {
    let temp = arr[leftIndex]
    while leftIndex < rightIndex {

        while leftIndex < rightIndex && temp <= arr[rightIndex] {
            rightIndex -= 1
        }
        if leftIndex < rightIndex {
            arr[leftIndex] = arr[rightIndex]
        }
        while leftIndex < rightIndex && arr[leftIndex] <= temp {
            leftIndex += 1
        }
        if leftIndex < rightIndex {
            arr[rightIndex] = arr[leftIndex]
        }
    }
    arr[leftIndex] = temp
    return leftIndex
}
複製程式碼

7.歸併排序(速度僅次於快速排序)

⒈將序列每相鄰兩個數字進行歸併操作(merge),形成floor(n/2)個序列,排序後每個序列包含兩個元素。 ⒉ 將上述序列再次歸併,形成floor(n/4)個序列,每個序列包含四個元素。 ⒊ 重複步驟2,直到所有元素排序完畢。

 public func mergeSort(arr: inout Array<Int>) {
    var tempArr: Array<Array<Int>> = []
    for item in arr {
       var subArr: Array<Int> = []
       subArr.append(item)
       tempArr.append(subArr)
    }
    while tempArr.count != 1 {
        var i = 0
        while i < tempArr.count - 1 {
            tempArr[i] = mergeTowArr(arr1: tempArr[i], arr2: tempArr[i+1])
            tempArr.remove(at : i+1)
            i += 1
        }
    }
 }

private func mergeTowArr(arr1: Array<Int>, arr2: Array<Int>) -> Array<Int> {
    var mergeArr: Array<Int> = []
    var firstIndex = 0
    var secondIndex = 0
    while firstIndex < arr1.count && secondIndex < arr2.count {
        if arr1[firstIndex]  < arr2[secondIndex] {
            merge.append(arr1[firstIndex])
            firstIndex += 1
        }else{
            merge.append(arr2[secondIndex])
            secondIndex += 1
        }
    }
    while firstIndex < arr1.count {
         merge.append(arr1[firstIndex])
         firstIndex += 1
    }
    while secondIndex < arr2.count {
         merge.append(arr2[secondIndex])
         secondIndex += 1
    }

    return mergeArr
}
複製程式碼

8.選擇排序

選擇排序(Selection sort)是一種簡單直觀的排序演算法。它的工作原理是每一次從待排序的資料元素中選出最小(或最大)的一個元素,存放在序列的起始位置,直到全部待排序的資料元素排完。 選擇排序是不穩定的排序方法(比如序列[5, 5, 3]第一次就將第一個[5]與[3]交換,導致第一個5挪動到第二個5後面)

public func selectSort(arr: inout Array<Int>) {
    for i in 0..<arr.count {
        var index = i
        for j in (i + 1)..<arr.count {
            if arr[index] > arr[j] {
                index = j
            }
        }
        if index != i {
            (arr[i],arr[index]) = (arr[index],arr[i])
        }
    }
}
複製程式碼

9.堆排序(選擇排序的一種)

通過headMakeFrom將陣列arr變為大頂堆,再把大頂堆的第一值和最後一個值交換,陣列長度減1。通過heapAdjast將交換後的陣列重新排序成大頂堆直到陣列長度為0。

public func heapSort(arr: inout Array<Int>) {//時間複雜度O(n*logn)
    var endIndex = arr.count - 1
    headMakeFrom(arr: &arr)

    while endIndex > 0 {
        (arr[0],arr[endIndex]) = (arr[endIndex],arr[0])
        heapAdjast(arr: &arr,starIndex: 1, arrLength: endIndex)
        endIndex -= 1
    }
}


private func heapMakeFrom(arr: inout Array<Int>) {
    var lastHead = arr.count/2
    while lastHead > 0 {
        heapAdjast(arr:  &arr, starIndex: lastHead, arrLenght: arr.count)
        lastHead -= 1
    }
}

private func heapAdjast(arr: Array<Int>, starIndex: Int, arrLength: Int) {
    var temp = arr[starIndex - 1]
    var parentIndex = starIndex
    var childIndex = 2 * parentIndex
    while childIndex <= arrLength {
        if childIndex < arrLength && arr[childIndex] > arr[childIndex - 1] {
            childIndex += 1
        }
        if arr[childIndex-1] > temp {
            arr[parentIndex - 1] = arr[childIndex - 1]
        }else{
            break 
        }
        parentIndex = childIndex
        childIndex = 2 * parentIndex 
    }
    arr[parentIndex - 1] = temp
}
複製程式碼

10. 生成指定尺寸的純色圖片

func imageWithColor(color: UIColor!, size: CGSize) -> UIImage{
    var size = size
    if CGSizeEqualToSize(size, CGSizeZero){
        size = CGSizeMake(1, 1)
    }
    let rect = CGRectMake(0, 0, size.width, size.height)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
複製程式碼

11- 修改圖片尺寸

func imageScaleToSize(image: UIImage, size: CGSize) -> UIImage{
    // 建立一個bitmap的context
    // 並把它設定成為當前正在使用的context
    // Determine whether the screen is retina
    if UIScreen.mainScreen().scale == 2.0{
        UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
    }else{
        UIGraphicsBeginImageContext(size)
    }

    // 繪製改變大小的圖片
    image.drawInRect(CGRectMake(0, 0, size.width, size.height))

    // 從當前context中建立一個改變大小後的圖片
    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()

    // 使當前的context出堆疊
    UIGraphicsEndImageContext()

    // 返回新的改變大小後的圖片
    return scaledImage
}
複製程式碼

12. 壓縮圖片大小

func imageCompress(originalImage: UIImage) -> UIImage{
    guard let imageData = UIImageJPEGRepresentation(originalImage, 0.5) else{
        return originalImage
    }

    let compressImage = UIImage(data: imageData)!
    return compressImage
}
複製程式碼

相關文章