Fork me on GitHub

iOS开发小技巧

获取Cell在tableView和当前屏幕中的位置

1
2
3
4
//获取某个cell在当前tableView上的坐标位置
CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
//获取cell在当前屏幕的位置
CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];

字符串UTF-8 编码与解码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// iOS9之前

// 编码
NSString *encodeStr = [@"你好世界" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 解码
NSString *decodeStr = [encodeStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// iOS9之后

// 编码
NSString *encodeStr = [@"你好世界" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

// 解码
NSString *decodeStr = [encodeStr stringByRemovingPercentEncoding];

渐变色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension UIColor {
class func gradientLeftToRightColor(_ leftColor:UIColor,_ rightColor : UIColor,_ viewW:CGFloat) -> UIColor {
let size = CGSize.init(width: viewW, height: 1)
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let context = UIGraphicsGetCurrentContext()
let colorspace = CGColorSpaceCreateDeviceRGB()
let colors = [leftColor.cgColor,rightColor.cgColor]
let gradient = CGGradient(colorsSpace: colorspace, colors: colors as CFArray, locations: nil)
context!.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: size.width, y: 0), options: CGGradientDrawingOptions(rawValue: 0))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIColor.init(patternImage:img!)
}
}

计算CollectionView高度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let s = Int(SCREEN_WIDTH/collectionItemWidth)
var n = dataSource.count/s
var h: CGFloat
if n != 0 {
if n == 1 {
if dataSource.count > s {
n += 1
}
} else {
n = dataSource.count % s == 0 ? n : n+1
}

h = CGFloat(n) * collectionItemHeight + CGFloat(n-1)*collectionItemSpace + topInset + bottomInset
}
else {
h = collectionItemHeight + topInset + bottomInset
}
collectionView.snp.remakeConstraints { (make) in
make.top.equalTo(bottomView).offset(WH(44+10))
make.left.right.equalTo(bottomView)
make.height.equalTo(WH(h))
}
collectionView.reloadData()
-------------本文结束感谢您的阅读-------------

本文作者:乔羽 / FightingJoey

发布时间:2018年09月23日 - 21:19

最后更新:2019年01月15日 - 19:37

原始链接:https://fightingjoey.github.io/2018/09/23/开发/iOS开发小技巧/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!