版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Alexander_Wei/article/details/77395420
/**
自定义button
*/
-(UIButton *)buttonType:(NSInteger)buttonType frame:(CGRect)frame addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents{
UIButton *button = [UIButton buttonWithType:buttonType];
button.frame = frame;
[button addTarget:target action:action forControlEvents:controlEvents];
return button;
}
/**
自定义label
*/
-(UILabel *)labelFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor textAlignment:(NSTextAlignment)textAlignment textColor:(UIColor *)textColor fontSize:(CGFloat)fontSize numberOfLines:(NSInteger)numberOfLines{
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.backgroundColor = backgroundColor;
label.textAlignment = textAlignment;
label.textColor = textColor;
label.font = [UIFont systemFontOfSize:fontSize];
label.numberOfLines = numberOfLines;
return label;
}
/**
自定义textField
*/
-(UITextField *)textFieldFrame:(CGRect)frame textAlignment:(NSTextAlignment)textAlignment fontSize:(CGFloat)fontSize textColor:(UIColor *)textColor backgroundColor:(UIColor *)backgroundColor placeholder:(NSString *)placeholder placeholderColor:(UIColor *)placeholderColor keyboardAppearance:(UIKeyboardAppearance)keyboardAppearance{
UITextField *textField = [[UITextField alloc] initWithFrame:frame];
textField.textAlignment = textAlignment;
textField.font = [UIFont systemFontOfSize:fontSize];
textField.textColor = textColor;
textField.backgroundColor = backgroundColor;
textField.placeholder = placeholder;
[textField setValue:placeholderColor
forKeyPath:@"_placeholderLabel.textColor"];
textField.keyboardAppearance = keyboardAppearance;
textField.autocorrectionType = UITextAutocorrectionTypeNo;//不开启自动更正功能
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;//首字母不大写
textField.tintColor = UICOLOR_RGB(13, 146, 125, 1);//设置光标颜色
//添加退出键盘的按钮
UIToolbar *keyboardBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 35)];
[keyboardBar setBarStyle:UIBarStyleDefault];
UIBarButtonItem *spaceBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[doneBtn setTitle:@"退出键盘" forState:UIControlStateNormal];
doneBtn.backgroundColor = [UIColor clearColor];
doneBtn.frame = CGRectMake(0,0,80,35);
[doneBtn addTarget:self action:@selector(callOutKeyboard) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *doneBtnItem = [[UIBarButtonItem alloc]initWithCustomView:doneBtn];
[keyboardBar setItems:@[spaceBtn,doneBtnItem]];
[textField setInputAccessoryView:keyboardBar];
return textField;
}
- (void)callOutKeyboard{
[[UIApplication sharedApplication].keyWindow endEditing:YES];
}
/**
设置文本CGSize
@param string 文本内容
@param fontSize 字体大小,需跟lable字体大小一致,否则会出现显示不全等问题
@param contentWidth 文本宽度
@param isBold 文本字体是否加粗
@param paragraphStyle 文字内容设计(间距等)
@return 文本CGSize
*/
-(CGSize)sizeForString:(NSString *)string fontOfSize:(CGFloat)fontSize contentWidth:(CGFloat)contentWidth bold:(BOOL)isBold paragraphStyle:(NSMutableParagraphStyle *)paragraphStyle{
UIFont *font;
if (isBold == YES) {
font = [UIFont boldSystemFontOfSize:fontSize];
}else{
font = [UIFont systemFontOfSize:fontSize];
}
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,paragraphStyle,NSParagraphStyleAttributeName,nil];
/*设置文本范围:
*boundingRectWithSize属性:限定文本在固定范围内进行显示
*contentWidth:代表最大宽度,到了最大宽度则换到下一行
*CGFLOAT_MAX:代表长度不限
*绘制文本时使用 NSStringDrawingUsesLineFragmentOrigin
*context属性:文本上下文。可调整字间距以及缩放等。最终,该对象包含的信息将用于文本绘制。该参数可为nil
*/
CGSize size = [string boundingRectWithSize:CGSizeMake(contentWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dictionary context:nil].size;
return size;
}
/**
判断是否为空字符串
@param string 需要判断的字符串
@return 结果
*/
-(BOOL)isBlankString:(NSString *)string{
if (string == nil || string == NULL) {
return YES;
}
if ([string isKindOfClass:[NSNull class]]) {
return YES;
}
if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
return YES;
}
return NO;
}
/**
中英文计算长度
@param string 需要计算长度的字符串
@return 长度
*/
-(NSInteger)convertToInt:(NSString *)string{
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData* data = [string dataUsingEncoding:encoding];
NSUInteger length = [data length];
return length;
}
/**
去除HTML标签
*/
-(NSString *)filterHTML:(NSString *)html{
NSScanner *scanner = [NSScanner scannerWithString:html];
NSString *text = nil;
while([scanner isAtEnd] == NO)
{
[scanner scanUpToString:@"<" intoString:nil];
[scanner scanUpToString:@">" intoString:&text];
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
//去除空格
html = [html stringByReplacingOccurrencesOfString:@" " withString:@""];
}
return html;
}
/**
调整UIWebView的图片大小
@param webView 需要调整的webView
*/
-(void)modifyImagesToFitScreen:(UIWebView *)webView{
//拦截网页图片,并修改图片大小
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth= document.body.offsetWidth;"
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}
/**
判断是否为正确的手机号
@param mobileStr 需要判断的手机号
@return 结果
*/
-(BOOL)isValidMobile:(NSString *)mobileStr{
if (mobileStr.length != 11)
{
return NO;
}
/**
* 手机号码:
* 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
* 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
* 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
* 电信号段: 133,149,153,170,173,177,180,181,189
*/
NSString *mobile = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
/**
* 中国移动:China Mobile
* 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
*/
NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
/**
* 中国联通:China Unicom
* 130,131,132,145,155,156,170,171,175,176,185,186
*/
NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
/**
* 中国电信:China Telecom
* 133,149,153,170,173,177,180,181,189
*/
NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobile];
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
if (([regextestmobile evaluateWithObject:mobileStr] == YES)
|| ([regextestcm evaluateWithObject:mobileStr] == YES)
|| ([regextestct evaluateWithObject:mobileStr] == YES)
|| ([regextestcu evaluateWithObject:mobileStr] == YES))
{
return YES;
}
else
{
return NO;
}
}
/**
判断是否为正确的身份证号
@param identityString 需要判断的身份证号
@return 结果
*/
-(BOOL)isValidIdentityString:(NSString *)identityString{
if (identityString.length != 18) return NO;
//正则表达式判断基本身份证号是否满足格式
NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
//如果通过该验证,说明身份证格式正确,但准确性还需计算
if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
//** 开始进行校验 *//
//将前17位加权因子保存在数组里
NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
//这是除以11后,可能产生的11位余数、验证码,也保存成数组
NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
//用来保存前17位各自乖以加权因子后的总和
NSInteger idCardWiSum = 0;
for(int i = 0;i < 17;i++) {
NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
idCardWiSum+= subStrIndex * idCardWiIndex;
}
//计算出校验码所在数组的位置
NSInteger idCardMod=idCardWiSum%11;
//得到最后一位身份证号码
NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
//如果等于2,则说明校验码是10,身份证号码最后一位应该是X
if(idCardMod==2) {
if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {
return NO;
}
}
else{
//用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码
if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
return NO;
}
}
return YES;
}
/**
邮箱验证
@param email 邮箱
@return 结果
*/
-(BOOL)isValidEmail:(NSString *)email{
BOOL stricterFilter = NO;
NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:email];
}
/**
获取当前时间
*/
-(NSString *)getCurrentDateStr{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSString* dateString = [dateFormatter stringFromDate:[NSDate date]];
return dateString;
}
/**
获取距离当前日期某年、某月、某日的日期
@param year 设置需要增加或减少的年
@param month 设置需要增加或减少的月
@param day 设置需要增加或减少的天数
@return 获取到的日期
*/
- (NSString *)getSomeDateStringWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
NSDate *currentDate = [NSDate date];//当前日期
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:currentDate];
[dateComponents setYear:year];
[dateComponents setMonth:month];
[dateComponents setDay:day];
NSDate *newDate = [calendar dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString *newDateString = [dateFormatter stringFromDate:newDate];
return newDateString;
}
/**
检测字符串是否含有特殊字符
@param string 需要检测的字符串
@return 结果
*/
-(BOOL)isSpecialCharactersIncluded:(NSString *)string{
//***需要过滤的特殊字符:~¥#&*<>《》()[]{}【】^@/£¤¥|§¨「」『』¢¬ ̄~@#¥&*()——+|《》$_€ . ?%
NSRange range = [string rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @"~¥#&*<>《》()[]{}【】^@/£¤¥|§¨「」『』¢¬ ̄~@#¥&*()——+|《》$_€.?%"]];
if (range.location == NSNotFound)
{
return NO;
}
return YES;
}
/**
判断是否是纯数字
*/
-(BOOL)isPureNumberString:(NSString *)string{
NSString *number = @"^[0-9]*$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", number];
BOOL result = [predicate evaluateWithObject:string];
return result;
}
/**
颜色值转换
@param hexColor 颜色值字符串
@return 转成的颜色
*/
-(UIColor*)hexColor:(NSString*)hexColor {
unsigned int red, green, blue, alpha;
NSRange range;
range.length = 2;
@try {
if ([hexColor hasPrefix:@"#"]) {
hexColor = [hexColor stringByReplacingOccurrencesOfString:@"#" withString:@""];
}
range.location = 0;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
range.location = 2;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
range.location = 4;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
if ([hexColor length] > 6) {
range.location = 6;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&alpha];
}
}
@catch (NSException *error) {
}
return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green/255.0f) blue:(float)(blue/255.0f) alpha:(float)(1.0f)];
}