extension String {
///返回字符串字符长度
func YhyStingLengthCount() -> Int{
return self.characters.count
}
///范围截取字符串 str[0...3]
subscript (r: Range) -> String {
get {
let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound)
return self[(startIndex ..< endIndex)]
}
}
//在字符串中查找另一字符串首次出现的位置
extension String {
//返回第一次出现的指定子字符串在此字符串中的索引
func positionOf(sub:String)->Int {
var pos = -1
if let range = range(of:sub) {
if !range.isEmpty {
pos = characters.distance(from:startIndex, to:range.lowerBound)
}
}
return pos
}
}
///往后截取字符串
func YhySubStringFrom(_ index:Int) -> String {
return self.substring(from: self.characters.index(self.startIndex, offsetBy: index))
}
///往前截取字符串
func YhySubStringTo(_ index:Int) -> String {
return self.substring(to: self.characters.index(self.startIndex, offsetBy: index))
}
}
//根据开始位置和长度截取字符串
extension String {
//根据开始位置和长度截取字符串
func subString(start:Int, length:Int = -1)->String {
var len = length
if len == -1 {
len = characters.count - start
}
let st = characters.index(startIndex, offsetBy:start)
let en = characters.index(st, offsetBy:len)
let range = st ..< en
return substring(with:range)
}
}
/**
* 重设图片大小
*/
extension UIImage {
func YhyReSizeImage(reSize:CGSize)->UIImage {
//UIGraphicsBeginImageContext(reSize);
UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale);
self.draw(in: CGRect(x: 0, y: 0, width: reSize.width, height: reSize.height))
let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext();
return reSizeImage;
}
/**
* 等比率缩放scaleSize一般设置0.5 , 0.8
*/
func scaleImage(scaleSize:CGFloat)->UIImage {
let reSize = CGSize(width: self.size.width * scaleSize, height: self.size.height * scaleSize)
return YhyReSizeImage(reSize: reSize)
}
}
///获取label文本高度
func contentSize() -> CGSize {
let size:CGSize
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = self.textAlignment
let attributes = [NSFontAttributeName:self.font,NSParagraphStyleAttributeName:paragraphStyle] as [String : Any]
size = (self.text! as NSString).boundingRect(with: CGSize(width: self.frame.size.width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size
return size
}
}