当前位置: 移动技术网 > IT编程>移动开发>IOS > IOS开发中常用的代码块收集整理

IOS开发中常用的代码块收集整理

2018年09月13日  | 移动技术网IT编程  | 我要评论

水产品养殖,曾文瀚,bl邪恶h全彩漫画集

收集常用的代码块是加快开发的有效途径,收集的操作步骤这里不在赘述,仅仅贡献上一些常用的功能性代码

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
 }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

  • ios uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网