1.使用定位时需要设置的权限
如果需要仅在前台定位,你在调用startUpdatingLocation 前需要调用 requestWhenInUseAuthorization 如果需要在后台定位,你在调用startUpdatingLocation前需要调用requestAlwaysAuthorization在plist文件中添加NSLocationWhenInUseUsageDescription或(与)NSLocationAlwaysUsageDescription字段:找到info.plist文件->右击->Open As->Source Code->在尾部的标签之前添加以下一个或两个:NSLocationWhenInUseUsageDescription需要定位NSLocationAlwaysUsageDescription需要定位
2.当button或者label上面的字数过多,想显示部分文字,后面的文字显示省略号的代码
self.locationBtn.titleLabel?.lineBreakMode = .ByTruncatingTail
3.IOS中设置button的时候,如果给button设置图片和文字,默认的是图片在左,文字在右,实现图片在右,文字在左的效果
self.shouBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 30, 0, -30)self.shouBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10)
4.textField限制小数点后俩位(该方法写在TextField代理方法中(shouldChangeCharactersInRange))
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) let expression = "^[0-9]*((\\.)[0-9]{0,2})?$" let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpressionOptions.AllowCommentsAndWhitespace) let numberOfMatches = regex.numberOfMatchesInString(newString, options:NSMatchingOptions.ReportProgress, range: NSMakeRange(0, (newString as NSString).length))
5.字体下面加下划线的代码
let content = NSMutableAttributedString.init(string:"以上代金券可用于分发给您的用户,如何获得以及如何分发给用户,请点击")content.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(long: NSUnderlineStyle.StyleSingle.rawValue), range: NSMakeRange(2,5))content.addAttribute(NSForegroundColorAttributeName, value: blue_color, range: NSMakeRange(2,5))content.addAttribute(NSUnderlineColorAttributeName, value: blue_color, range: NSMakeRange(2,5))mess.attributedText = content
6.调用系统电话打电话代码
let callWebView = UIWebView()let tel = “18020009876”let telStr = String(format:"tel://%@",tel!)let url = NSURL(string: telStr)callWebView.loadRequest(NSURLRequest(URL: url!))self.view.addSubview(callWebView)
7.使用工具reveal时,将静态包拖入工程,并且在build setting中的other linker flags中添加-ObjC -lz -framework Reveal字段
8.swift中label自适应高度的代码(特别注意:手动设置的字体和xib中的字体保持一致)
let size = CGSize(width: ScreenW - 16,height:CGFloat(MAXFLOAT))rect = data.ac_description.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: NSDictionary(object:UIFont.systemFontOfSize(13), forKey: NSFontAttributeName) as? [String : AnyObject], context: nil)
9.手机号判断
let phoneRegex = "^1[0-9]{10}$” //正则 let phoneText = NSPredicate(format:"SELF MATCHES %@",phoneRegex) if phoneText.evaluateWithObject(telephoneText) == false { HUD.hidden = false HUD.labelText = "请输入正确的手机号" HUD.hide(true, afterDelay: 1) }
10.获取图片格式的代码
func typeForImageData(data:AnyObject)->NSString { var c = uint_fast8_t() data.getBytes(&c, length: 1) switch (c) { case 0x89: return "image/png" case 0x47: return "image/gif" case 0xFF: return "image/jpeg" case 0x4D: return "image/tiff" default: return "image/jpeg" } }
11.UIImage转base64代码
let data = UIImageJPEGRepresentation(image!, 0.1)let encImageStr = data!.base64EncodedDataWithOptions(.Encoding64CharacterLineLength) let str = String(data: encImageStr, encoding:NSASCIIStringEncoding)! letstr1 = str.stringByReplacingOccurrencesOfString("\r\n", withString: "")
12.字符串分割
let str = "name=zhangsan"let array = str.componentsSeparatedByString("=")
13.隐藏手机号中间的四位号码
NSString *originTel = @"13722223333";NSString *tel = [originTel stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
14.设置顶部状态栏
override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent }
15.更改导航栏上面返回按钮的颜色和标题的字体和颜色的方法self.navigationController?.navigationBar.tintColor = UIColor.init(red: 186/255.0, green: 186/255.0, blue: 186/255.0, alpha: 1)let navigationTitleAttribute: NSDictionary = NSDictionary(object: UIColor.init(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 1.0), forKey: NSForegroundColorAttributeName)self.navigationController?.navigationBar.titleTextAttributes = navigationTitleAttribute as? [String : AnyObject]
16.当URL中有转移字符或者有中文的时候,使用如下方法对其进行转义
1.url编码ios中http请求遇到汉字的时候,需要转化成UTF-8,用到的方法是:NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2.url解码请求后,返回的数据,如果显示的是这样的格式:%3A%2F%2F,此时需要我们进行UTF-8解码,用到的方法是:NSString *str = [model.album_name stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
17.将数组或者字典转换为json串的方法如下
let dic = NSMutableDictionary()dic.setValue("123", forKey: "direct1")dic.setValue("30", forKey: "money")let dic1 = NSMutableDictionary()dic1.setValue("123", forKey: "direct1")dic1.setValue("456", forKey: "direct2")dic1.setValue("50", forKey: "money")let dic2 = NSMutableDictionary()dic2.setValue("123", forKey: "direct1")dic2.setValue("456", forKey: "direct2")dic2.setValue("789", forKey: "direct3")dic2.setValue("100", forKey: "money")let array = [dic,dic1,dic2]let data = try! NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions.PrettyPrinted)goodsList = String(data: data, encoding: NSUTF8StringEncoding)!
18.将时间戳转换为字符串的代码
let string = NSString(string: self.data.createDate!)let time:NSTimeInterval = string.doubleValuelet formatter = NSDateFormatter()formatter.dateFormat = "yyyy-MM-dd"let date = NSDate(timeIntervalSince1970: time)self.dateLabel.text = formatter.stringFromDate(date)
19.swift中如何获取当前月份的代码
let currentDate = NSDate()let dateFormatter = NSDateFormatter()dateFormatter.dateFormat = "MM"let dateString = dateFormatter.stringFromDate(currentDate)
20.将系统时间转换为时间戳的代码
let date = NSDate()
let datsStr = date.timeIntervalSince1970
21.使用cocoaPods导入第三方库
platform :ios, '8.0'
use_frameworks!
target 'ylAppiOSnative' do //单引号里面的内容是工程名pod 'AFNetworking','~> 3.1.0'
pod 'Masonry','~> 1.0.0'
pod 'MJRefresh', '~> 3.1.0'
pod 'MBProgressHUD', '~> 0.9.2'
pod 'SDWebImage','~> 3.7.5'
pod 'SDCycleScrollView','~> 1.62'
end
22.改变textField的placeholder颜色的方法
_consigneeField.placeholder = @"请输入收货人姓名";
[_consigneeField setValue:[UIColor colorWithRed:115/255.0 green:115/255.0 blue:115/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];[_consigneeField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];