swift 截取字符串


swift3.0 使用String.Index來做位置索引,要想實現截取功能首先得獲取到String.Index;

獲取中間部分參數用Range<Index>即可;

let str:String = btn.currentTitle ?? ""

         let indes = str.index(str.startIndex, offsetBy: str.length - 1)

         let prefix = str.substring(to: indes)

         btn.setTitle(prefix + "▾", for: .normal)

舉例從開始截取到倒數第二位。

let index = str.index(str.endIndex, offsetBy: -5)
        
    let suffix = str.substring(from: index)

截取倒數五位

2.富文本設置 (空格也會占位)

      guard let mingzi = model.name,let jieshao = model.bio else {

         return

      }

      let amountString = NSMutableAttributedString(string:"\(mingzi)/\(jieshao)")

      //設置字體顏色

      amountString.addAttribute(NSForegroundColorAttributeName, value: UIColor.black,range: NSMakeRange(0, "\(mingzi)".length + 1))

      amountString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 13),range: NSMakeRange(0, "\(mingzi)".length + 1))

      

      amountString.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray,range: NSMakeRange(1 + "\(mingzi)".length, "\(jieshao)".length))

      amountString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 13),range: NSMakeRange(1 + "\(mingzi)".length, "\(jieshao)".length))

      self.bio.attributedText = amountString


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM