ios开发常用小代码(不定期更新)

代码中含有多为swift语法,少部分为objective-c语法

tableView Cell的动态高度

在自定义cell里面可以在extension写一个方法来获取动态高度

1
2
3
4
5
6
7
8
extension MyCustomCell {
func getCellDynamicHeight() -> CGFloat {
self.layoutIfNeeded()
//todo:添加自己要计算的高度算法,返回一个CGFloat值
var aCFloatValue = 0
return aCFloatValue
}
}

然后在自己的tableView的delegate的以下方法写上如下代码:

1
2
3
4
5
6
7
8
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
//从下面这个方法获取当前cell,然后调用cell的getCellDynamicHeight()方法
var customCell = self.tableView(tableView, cellForRowAtIndexPath: indexPath) as? MyCustomCell
if let cell = customCell {
return cell.getCellDynamicHeight()
}
return 0
}

设置textView行间距,文本颜色,字符间距等

textView根据文本长度动态获取高度(label文本控件同理)
以下语句利用attributedString来设置行间距,文本颜色,其中textView为需要设置的控件变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var intro = textView.text as NSString
var attributedStr = NSMutableAttributedString(string:intro)
var style = NSMutableParagraphStyle()
attributedStr.addAttribute( //改变字体
NSFontAttributeName,
value: UIFont(name: "FZLanTingHeiS-R-GB", size: 16)!,
range: NSMakeRange(0, intro.length))
attributedStr.addAttribute( //文本颜色
NSForegroundColorAttributeName,
value: UIColor(red: 134/255, green: 135/255, blue: 139/255, alpha: 1),
range: NSMakeRange(0, intro.length))
style.lineSpacing = 5
attributedStr.addAttribute( //行间距
NSParagraphStyleAttributeName,
value: style,
range: NSMakeRange(0, attributedStr.length))
attributedStr.addAttribute( //字符间距
NSKernAttributeName,
value: NSNumber(float: 1),
range: NSMakeRange(0, str.length))
textView.attributedText = attributedStr

然后利用boundingRectWithSize()这个方法来计算包含行间距,字体大小等参数的文本的高度。其中CGSizeMake(width,0)参数表示在width(一般为控件宽度)宽的rect中算出文本的height,而attribute字典中则包含字体大小,字体行间距等计算参数

1
2
3
4
5
var size = contentText.attributedText.boundingRectWithSize(
CGSizeMake(UIScreen.mainScreen().bounds.width - 10 - 14 , 0),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
context: nil)
var height = size.height //此处获得算出来的文本高度

tableView Header的展开动画

步骤1.设置tableView.tableHeaderView = customHeaderView;2.在展开后把Frame改变了的Header重新赋值给tableView。
下面代码是放在customHeaderView中,当点击展开代按钮后

1
2
3
4
5
6
7
func onclickExpandButton(sender: AnyObject) {    
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.frame = CGRectMake(0, 0, expandWidth, expandHeight)
(self.superview as! UITableView).tableHeaderView = self //Frame改变了的Header重新赋值给tableView
self.superview?.layoutIfNeeded()
})
}

swift的MD5加密

先把这个添加到项目中:libcommonCrypto.dylib

然后在项目的bridge文件里面:

1
#import <CommonCrypto/CommonCrypto.h>

定义一个尾部,其实就是给字符串增加一些固定的信息

1
2
//用于md5加密的尾部
let MD5_BASE_TAIL = "tail"

然后给String类做一个extension

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
extension String {
var md5_with_tail: String! {
get{
var orginStr = self + MD5_BASE_TAIL
let str = orginStr.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(orginStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)

CC_MD5(str!, strLen, result)

var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}

result.dealloc(digestLen)
var md5_result = String(format: hash as String)
return md5_result
}
}
}

最后这样调用就可以得到加密后的字符串了

1
2
var str : String = "abc"
var str_md5 = str.md5_with_tail

textField内边距

代码为左边距,同样可以设置右边距

1
2
3
4
func setTextFieldMargins(textField:UITextField){
textField.leftView = UIView(frame: CGRectMake(0, 0, 8, textField.frame.size.height))
textField.leftViewMode = UITextFieldViewMode.Always
}

类似推送的顶部弹出Toast提示框

写一个extension:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//用于实现顶部弹出的提示
extension UIWindow {
func showToast(message:String){

var toastView = getToastView(message)
toastView.transform = CGAffineTransformMakeTranslation(0, -toastView.frame.height)
self.addSubview(toastView)
//设置在状态栏之上
self.windowLevel = UIWindowLevelAlert
//动画
UIView.animateWithDuration(
0.2,
delay: 0,
options: .CurveEaseOut,
animations: { () -> Void in
toastView.transform = CGAffineTransformIdentity

}) { (finished) -> Void in
var timer = NSTimer.scheduledTimerWithTimeInterval(
1.35,
target: self,
selector: "toastTimerDidFinish:",
userInfo:toastView, repeats: false)
}
}

func toastTimerDidFinish(timer:NSTimer){
self.hideToast(timer.userInfo as! UIView)
}

func hideToast(toast:UIView){
UIView.animateWithDuration(
0.2,
delay: 0,
options: .CurveEaseIn,
animations: { () -> Void in
toast.transform = CGAffineTransformMakeTranslation(0, -toast.frame.height)
}) { (finished) -> Void in
self.windowLevel = UIWindowLevelNormal
toast.removeFromSuperview()
}
}


private func getToastView(message:String) -> UIView{

//参数获取或定义
var screenBounds = UIScreen.mainScreen().bounds
var topMargin :CGFloat = 4
var fontSize: CGFloat = 14

//计算文本高度
var labelHeight = (message as NSString).boundingRectWithSize(
CGSizeMake(screenBounds.width,0),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName : UIFont.systemFontOfSize(fontSize)],
context: nil).height

//配置label
var label = UILabel(frame: CGRectMake(0, topMargin, screenBounds.width, labelHeight))
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 0
label.font = UIFont(name: "FZLanTingHeiS-R-GB", size: fontSize) ?? UIFont.systemFontOfSize(fontSize)
label.backgroundColor = UIColor.clearColor()
label.textColor = UIColor.whiteColor()
label.text = message

//配置toastView
var toastView = UIView(frame: CGRectMake(0, 0, screenBounds.width, labelHeight + topMargin * 2 ))
toastView.backgroundColor = UIColor.blackColor()
toastView.alpha = 0.95
toastView.addSubview(label)

return toastView
}
}

用法:

1
UIApplication.sharedApplication().keyWindow?.showToast("hello")