IOS开发中常用的代码块收集整理
程序员文章站
2022-09-02 23:15:50
收集常用的代码块是加快开发的有效途径,收集的操作步骤这里不在赘述,仅仅贡献上一些常用的功能性代码
1、与高度和宽度有关的
/*获取导航栏高度*/
public func getnaviga...
收集常用的代码块是加快开发的有效途径,收集的操作步骤这里不在赘述,仅仅贡献上一些常用的功能性代码
1、与高度和宽度有关的
/*获取导航栏高度*/ public func getnavigationbarheight() -> cgfloat { let navrect:cgrect! = self.navigationcontroller?.navigationbar.frame return navrect.size.height } /*获取标签栏高度*/ public func gettabbarheight() -> cgfloat { let tabbarrect:cgrect! = self.tabbarcontroller?.tabbar.frame return tabbarrect.size.height } /*获取状态栏高度*/ public func getstatusbarheight() -> cgfloat { let rectstatus:cgrect = uiapplication.shared.statusbarframe return rectstatus.size.height } /*根据提供的字体大小,宽度获取字文字的高度*/ func gettextheigh(textstr:string,font:uifont,width:cgfloat) -> cgfloat { let normaltext: nsstring = textstr as nsstring let size = cgsize(width: width, height: 10000) let dic:nsdictionary = nsdictionary(object: font, forkey: nsattributedstringkey.font as nscopying) let stringsize = normaltext.boundingrect(with: size, options: .useslinefragmentorigin, attributes: dic as? [nsattributedstringkey : any], context:nil).size return stringsize.height } /*提供文字大小,控件高度,获取到文字的宽度*/ func gettexwidth(textstr:string,font:uifont,height:cgfloat) -> cgfloat { let normaltext: nsstring = textstr as nsstring let size = cgsize(width: 10000, height: height) let dic:nsdictionary = nsdictionary(object: font, forkey: nsattributedstringkey.font as nscopying) let stringsize = normaltext.boundingrect(with: size, options: .useslinefragmentorigin, attributes: dic as? [nsattributedstringkey : any], context:nil).size return stringsize.width + 40 } uiscreen.main.bounds.size.width // 屏幕宽度 uiscreen.main.bounds.size.height // 屏幕高度 /*uifont的适配(创建uifont的扩展)*/ + (void)load { method newmethod = class_getclassmethod([self class], @selector(adjustfont:)); method method = class_getclassmethod([self class], @selector(systemfontofsize:)); method_exchangeimplementations(newmethod, method); } + (uifont *)adjustfont:(cgfloat)fontsize { uifont *newfont = nil; //basewidth 为设计图的尺寸 newfont = [uifont adjustfont:fontsize * [uiscreen mainscreen].bounds.size.width / basewidth]; return newfont; }
2、处理类相关
/*十六进制颜色*/ func rgbcolorfromhex(rgbvalue: int) -> (uicolor) { return uicolor(red: ((cgfloat)((rgbvalue & 0xff0000) >> 16)) / 255.0, green: ((cgfloat)((rgbvalue & 0xff00) >> 8)) / 255.0, blue: ((cgfloat)(rgbvalue & 0xff)) / 255.0, alpha: 1.0) } /*时间戳转化成自定义时间格式*/ func gettimewithtimeinterval(timeinterval:timeinterval, dataformart:string) -> string { let date:date = date(timeintervalsince1970: timeinterval / 1000) let formatter:dateformatter = dateformatter.init() formatter.dateformat = dataformart let timestr:string = formatter.string(from: date) return timestr } /*字符串md5加密*/ - (nsstring *)md5string:(nsstring *)str { if (!str) return nil; const char *cstr = str.utf8string; unsigned char result[cc_md5_digest_length]; cc_md5(cstr, (cc_long)strlen(cstr), result); nsmutablestring *md5str = [nsmutablestring string]; for (int i = 0; i < cc_md5_digest_length; ++i) { [md5str appendformat:@"%02x", result[i]]; } return md5str; } /*微信支付签名*/ -(nsstring *)createmd5singforpaywithappid:(nsstring *)appid_key partnerid:(nsstring *)partnerid_key prepayid:(nsstring *)prepayid_key package:(nsstring *)package_key noncestr:(nsstring *)noncestr_key timestamp:(uint32)timestamp_key{ nsmutabledictionary *signparams = [nsmutabledictionary dictionary]; [signparams setobject:appid_key forkey:@"appid"];//微信appid 例如wxfb132134e5342 [signparams setobject:noncestr_key forkey:@"noncestr"];//随机字符串 [signparams setobject:package_key forkey:@"package"];//扩展字段 参数为 sign=wxpay [signparams setobject:partnerid_key forkey:@"partnerid"];//商户账号 [signparams setobject:prepayid_key forkey:@"prepayid"];//此处为统一下单接口返回的预支付订单号 [signparams setobject:[nsstring stringwithformat:@"%u",timestamp_key] forkey:@"timestamp"];//时间戳 nsmutablestring *contentstring =[nsmutablestring string]; nsarray *keys = [signparams allkeys]; nsarray *sortedarray = [keys sortedarrayusingcomparator:^nscomparisonresult(id obj1, id obj2) { return [obj1 compare:obj2 options:nsnumericsearch]; }]; for (nsstring *categoryid in sortedarray) { if (![[signparams objectforkey:categoryid] isequaltostring:@""] && ![[signparams objectforkey:categoryid] isequaltostring:@"sign"] && ![[signparams objectforkey:categoryid] isequaltostring:@"key"] ) { [contentstring appendformat:@"%@=%@&", categoryid, [signparams objectforkey:categoryid]]; } } [contentstring appendformat:@"key=%@", @"utno9lvl7lgmhfloal8yo6orrkio2iky"]; nsstring *result = [self md5string:contentstring]; return result; } /*去除字符串的空格和换行符*/ + (nsstring *) handlenewlineandwhitspaceforstring:(nsstring *)str;{ str = [str stringbyreplacingoccurrencesofstring:@"\r" withstring:@""]; str = [str stringbyreplacingoccurrencesofstring:@"\n" withstring:@""]; str = [str stringbyreplacingoccurrencesofstring:@" " withstring:@""]; return str; } /*数组去除重复数据*/ public extension array { func filterduplicates(_ filter: (element) -> e) -> [element] { var result = [element]() for value in self { let key = filter(value) if !result.map({filter($0)}).contains(key) { result.append(value) } } return result } } /*图片二维码识别(使用zxing)*/ + (void)recognizeimage:(uiimage*)image block:(void(^)(zxbarcodeformat barcodeformat,nsstring *str))block { zxcgimageluminancesource *source = [[zxcgimageluminancesource alloc] initwithcgimage:image.cgimage]; zxhybridbinarizer *binarizer = [[zxhybridbinarizer alloc] initwithsource: source]; zxbinarybitmap *bitmap = [[zxbinarybitmap alloc] initwithbinarizer:binarizer]; nserror *error; id reader; if (nsclassfromstring(@"zxmultiformatreader")) { reader = [nsclassfromstring(@"zxmultiformatreader") performselector:@selector(reader)]; } zxdecodehints *_hints = [zxdecodehints hints]; zxresult *result = [reader decode:bitmap hints:_hints error:&error]; if (result == nil) { block(kbarcodeformatqrcode,nil); return; } block(result.barcodeformat,result.text); } /*swift执行一次的dispatch_once函数*/ public extension dispatchqueue { private static var _oncetracker = [string]() public class func once(key: string, block:()->void) { objc_sync_enter(self) defer { objc_sync_exit(self) } if _oncetracker.contains(key) { return } _oncetracker.append(key) block() } } /*扩大按钮响应区域(创建uibutton扩展)*/ static char topnamekey; static char rightnamekey; static char bottomnamekey; static char leftnamekey; - (void)setenlargeedgewithtop:(cgfloat) top right:(cgfloat) right bottom:(cgfloat) bottom left:(cgfloat) left { objc_setassociatedobject(self, &topnamekey, [nsnumber numberwithfloat:top], objc_association_copy_nonatomic); objc_setassociatedobject(self, &rightnamekey, [nsnumber numberwithfloat:right], objc_association_copy_nonatomic); objc_setassociatedobject(self, &bottomnamekey, [nsnumber numberwithfloat:bottom], objc_association_copy_nonatomic); objc_setassociatedobject(self, &leftnamekey, [nsnumber numberwithfloat:left], objc_association_copy_nonatomic); } - (void)setenlargeedge:(cgfloat) size { objc_setassociatedobject(self, &topnamekey, [nsnumber numberwithfloat:size], objc_association_copy_nonatomic); objc_setassociatedobject(self, &rightnamekey, [nsnumber numberwithfloat:size], objc_association_copy_nonatomic); objc_setassociatedobject(self, &bottomnamekey, [nsnumber numberwithfloat:size], objc_association_copy_nonatomic); objc_setassociatedobject(self, &leftnamekey, [nsnumber numberwithfloat:size], objc_association_copy_nonatomic); } - (cgrect) enlargedrect { nsnumber* topedge = objc_getassociatedobject(self, &topnamekey); nsnumber* rightedge = objc_getassociatedobject(self, &rightnamekey); nsnumber* bottomedge = objc_getassociatedobject(self, &bottomnamekey); nsnumber* leftedge = objc_getassociatedobject(self, &leftnamekey); if (topedge && rightedge && bottomedge && leftedge) { return cgrectmake(self.bounds.origin.x - leftedge.floatvalue, self.bounds.origin.y - topedge.floatvalue, self.bounds.size.width + leftedge.floatvalue + rightedge.floatvalue, self.bounds.size.height + topedge.floatvalue + bottomedge.floatvalue); } else { return self.bounds; } } - (uiview*) hittest:(cgpoint) point withevent:(uievent*) event { cgrect rect = [self enlargedrect]; if (cgrectequaltorect(rect, self.bounds)) { return [super hittest:point withevent:event]; } return cgrectcontainspoint(rect, point) ? self : nil; } /*获取唯一设备号*/ +(nsstring *) getdevicetoken { nserror *error; nsstring *devicenumber; devicenumber = [sskeychain passwordforservice:@"laihudong.app" account:@"devicetoken" error:&error]; if(error){ nslog(@"出现错误"); } if (devicenumber == nil ||[devicenumber isequaltostring:@""]) { cfuuidref uuidref = cfuuidcreate(kcfallocatordefault); cfstringref stringref = cfuuidcreatestring(kcfallocatordefault, uuidref); [sskeychain setpassword:[nsstring stringwithformat:@"%@", stringref] forservice:@"laihudong.app" account:@"devicetoken"]; devicenumber = [nsstring stringwithformat:@"%@",stringref]; } return devicenumber; }
3、验证类相关
/*验证手机号*/ class func validatephononum(phonenumber:string) -> bool { let mobil = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"; let cm = "^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$"; let cu = "^1(3[0-2]|5[256]|8[56])\\d{8}$"; let ct = "^1((33|53|8[019])[0-9]|349)\\d{7}$"; let regextestmobile = nspredicate(format: "self matches %@", mobil) let regextestcm = nspredicate(format: "self matches %@", cm) let regextestcu = nspredicate(format: "self matches %@", cu) let regextestct = nspredicate(format: "self matches %@", ct) if regextestmobile.evaluate(with: phonenumber)||regextestcm.evaluate(with: phonenumber)||regextestcu.evaluate(with: phonenumber)||regextestct.evaluate(with: phonenumber) { return true } return false } /*验证身份证号*/ class func validateidcard(idcardnumber:string) -> bool { let pattern = "(^[0-9]{15}$)|([0-9]{17}([0-9]|x)$)"; let pred = nspredicate(format: "self matches %@", pattern) let ismatch:bool = pred.evaluate(with: idcardnumber) return ismatch; } /*验证邮箱*/ -(bool)isvalidateemail:(nsstring *)email { nsstring *emailregex = @"[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,4}"; nspredicate *emailtest = [nspredicate predicatewithformat:@"selfmatches%@",emailregex]; return [emailtest evaluatewithobject:email]; } /*判断事时间后*/ class func validatetimeinterval(timeinterval:timeinterval) -> bool { var isbefore:bool! let orderdate:date = date.init(timeintervalsince1970: timeinterval / 1000) let currentdate:date = date.init(timeintervalsincenow: 0) /*时间判断*/ if orderdate.compare(currentdate) == .orderedascending { isbefore = false } if orderdate.compare(currentdate) == .orderedsame { isbefore = false } if orderdate.compare(currentdate) == .ordereddescending { isbefore = true } return isbefore } /*判断当前周几*/ class func getweekday() -> int { let dateformatter:dateformatter = dateformatter.init() dateformatter.dateformat = "yyyy-mm-dd hh:mm:ss" let date:date = date.init(timeintervalsincenow: 0) let interval = int(date.timeintervalsince1970) let days = int(interval/86400) let weekday = ((days + 4)%7+7)%7 return weekday == 0 ? 7 : weekday }
上一篇: Android放置图片内存溢出处理方法
下一篇: 后台日志管理和网站信息设计