swift 截取字符串

swift3.0 使用String.Index来作位置索引,要想实现截取功能首先得获取到String.Index;swift

获取中间部分参数用Range<Index>便可;字体

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

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

         let prefix = str.substring(to: indes)string

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

举例从开始截取到倒数第二位。io

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

截取倒数五位model

2.富文本设置 (空格也会占位)tab

      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

相关文章
相关标签/搜索