Swift 字符串工具类

网络请求的时候会将get中的字符串进行URL转换

func URLEncodedString() -> String? {
        let customAllowedSet =  NSCharacterSet(charactersInString:"!$&'()*+,-./:;=?@_~%#[]").invertedSet
        let escapedString = self.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
        return escapedString
    }

计算文字的高度

func sizeForString(Width width:CGFloat,andFontSize fontSize:CGFloat) -> CGSize {
        let tempNSString = NSString(string: self.trimString())
        let sizeBase:CGSize = CGSizeMake(width, CGFloat.max)
        let options: NSStringDrawingOptions = [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine]
        let style = NSMutableParagraphStyle()
        style.lineBreakMode = .ByCharWrapping
        let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(fontSize),NSParagraphStyleAttributeName:style]
        let rectForString:CGRect = tempNSString.boundingRectWithSize(sizeBase, options: options, attributes: attributes , context: nil)
        return rectForString.size
    }

attribute文字的高度计算

static func sizeForAttributeString(string:NSAttributedString,andWidth width:CGFloat) -> CGSize {
        let sizeBase:CGSize = CGSizeMake(width, CGFloat.max)
        let options: NSStringDrawingOptions = [.UsesLineFragmentOrigin, .UsesFontLeading]
        let rectForString:CGRect = string.boundingRectWithSize(sizeBase, options: options, context: nil)
        return rectForString.size
    }






转载于:https://my.oschina.net/wupengnash/blog/656431

你可能感兴趣的:(Swift 字符串工具类)