个人链接
- 博客园主页 : 博客园主页
- GitHub : 我的GitHub
- iOS程序猿(媛)~~ : 这是我个人整理的一个技术专题, 这里的文章都是比较有技术含量(不断更新)!
- 微信公众号 :
最近在搭建新项目,为了方便开发,常会用到一些宏定义,梳理了之前项目中用到,又查漏补缺挑选了一些网络上比较不错的,总结了一份分享给大家。
功能目录:
1.强制使用系统键盘;
//在AppDelegate中写:
//强制使用系统键盘 >=iOS8
- (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier{
if ([extensionPointIdentifier isEqualToString:@"com.apple.keyboard-service"]) {
return NO;
}
return YES;
}
2.去除数组中相同的元素;
//去除数组中相同的元素
NSArray *oldArr = @[@"12",@"123",@"123"];
NSArray *newArr = [oldArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"====%@====",newArr);
3.修改textField的placeholder的字体颜色、大小;
//修改textField的placeholder的字体颜色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font”];
4.获取app缓存大小;
//获取app缓存大小
- (CGFloat)getCachSize {
NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
//获取自定义缓存大小
//用枚举器遍历 一个文件夹的内容
//1.获取 文件夹枚举器
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
__block NSUInteger count = 0;
//2.遍历
for (NSString *fileName in enumerator) {
NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
count += fileDict.fileSize;//自定义所有缓存大小
}
// 得到是字节 转化为M
CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
return totalSize;
}
5.获取手机和app信息;
//获取手机和app信息
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSLog(@"app_Name: %@",app_Name);
// app版本
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"app_Version: %@",app_Version);
// app build版本
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
NSLog(@"app_build: %@",app_build);
//手机序列号
NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString];
NSLog(@"手机序列号: %@",identifierNumber);
//手机别名: 用户定义的名称
NSString* userPhoneName = [[UIDevice currentDevice] name];
NSLog(@"手机别名: %@", userPhoneName);
//设备名称
NSString* deviceName = [[UIDevice currentDevice] systemName];
NSLog(@"设备名称: %@",deviceName );
//手机系统版本
NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
NSLog(@"手机系统版本: %@", phoneVersion);
//手机型号
NSString* phoneModel = [[UIDevice currentDevice] model];
NSLog(@"手机型号: %@",phoneModel );
//地方型号 (国际化区域名称)
NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];
NSLog(@"国际化区域名称: %@",localPhoneModel);
6.当tableView占不满一屏时,去除下边多余的单元格;回滚到顶部
//当tableView占不满一屏时,去除下边多余的单元格
self.tableView.tableHeaderView = [UIView new];
self.tableView.tableFooterView = [UIView new];
//回滚到顶部
[self.tableView setContentOffset:CGPointMake(0,0) animated:NO];
7.删除NSUserDefaults所有记录;
//删除NSUserDefaults所有记录
//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二
- (void)resetDefaults {
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
}
// 方法三
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
8.禁用系统滑动返回功能;
//禁用系统滑动返回功能
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
return NO;
}
9.UIView背景颜色渐变,圆角阴影,虚线;
//UIView背景颜色渐变
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 100, HitoScreenW-20, 200)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
// 左上角和右上角添加圆角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
//为一个view添加虚线边框
CAShapeLayer *border = [CAShapeLayer layer];
border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
border.fillColor = nil;
border.lineDashPattern = @[@4, @2];
border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;
border.frame = view.bounds;
[view.layer addSublayer:border];
10.让手机震动一下;
//让手机震动一下
//导入框架#import
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
//或者
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
11.在状态栏增加网络请求的菊花,类似safari加载网页的时候状态栏菊花;
//在状态栏增加网络请求的菊花,类似safari加载网页的时候状态栏菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
12.打开摇一摇功能;
//1、打开摇一摇功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
//2、让需要摇动的控制器成为第一响应者
[self becomeFirstResponder];
//3、实现以下方法
// 开始摇动
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"开始摇动");
}
// 取消摇动
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"取消摇动");
}
// 摇动结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"摇动结束");
}
13.导航栏隐藏和显示功能,统一设置导航栏颜色和导航栏字体的颜色;
//隐藏导航栏
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]forBarMetrics:UIBarMetricsDefault];
//去掉黑线
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
对立的方法:—>
//显示导航栏
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//加上黑线
[self.navigationController.navigationBar setShadowImage:nil];
具体方法实现 :
#pragma mark -- 将导航栏隐藏
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//隐藏导航栏
[self.navigationController.navigationBar setShadowImage:[UIImage new]];//去除黑线
}
#pragma mark -- 将导航栏归还原样
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];//显示导航栏
[self.navigationController.navigationBar setShadowImage:nil];//加上黑线
}
(统一设置导航栏颜色和导航栏字体的颜色)
self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
//统一设置导航栏样式,文字颜色及其大小
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
[[UINavigationBar appearance]setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}];
[[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:20]}];
14.关于iOS自定义返回按钮右滑返回手势失效的解决;
(关于iOS自定义返回按钮右滑返回手势失效的解决)
self.navigationController.interactivePopGestureRecognizer.delegate=(id)self;
15.苹果系统自带分享功能;
需要导入头文件 :
#import
//苹果系统自带分享功能
UIActivityViewController *avc = [[UIActivityViewController alloc]initWithActivityItems:@[@"分享内容名称",[NSURL URLWithString:@"[https://github.com/NSLog-YuHaitao/iOSReview](https://github.com/NSLog-YuHaitao/iOSReview)"]] applicationActivities:nil];
[self presentViewController:avc animated:YES completion:nil];
- iOS中文网址路径转换URLEncode;
//拼接数据请求时,出现汉字的解决办法
NSString* encodedString = [urlStringstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
17.两个库有冲突;运行Xcode后,会打印一堆东西;
两个库有冲突
设置Xcode中Targets选项下有Other linker flags的设置: -force_load
xcode中后台打印一堆东西,修改办法
OS_ACTIVITY_MODE disable
18.iOS开发,生成随机数;
获取一个随机整数范围在:[0,100)包括0,不包括100
int x = arc4random() % 100;
19.设置Btn上文字对其方式(例子:左对齐及左边距);
设置Btn上文字对其方式(例子:左对齐及左边距)
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
20.实现通知传值;
实现通知传值
第二个界面:
//注册观察者
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(achiveMessage:) name:@"sendMessage" object:nil];
//实现通知方法
-(void)achiveMessage:(NSNotification *)noti{
NSDictionary * dic = noti.userInfo;
//获得消息之后,通知获得之后
//获取label 给lable赋值
NSLog(@"%@",dic[@"pass"]);
}
//移除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"sendMessage" object:nil];
}
第一个界面:
//发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"sendMessage" object:self userInfo:@{@"pass":要传递的东西}];
21.iOS如何将父视图透明,而内容不透明的方法;
iOS如何将父视图透明,而内容不透明的方法
self.view.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.7f];
我们只设置了背景是透明的,没有全局的设置view的透明属性,就能使得添加到view的所有子试图保持原来的属性,不会变成透明的
22.如何设置label上面的文字显示不同颜色;
如何设置label上面的文字显示不同颜色
//label上的文字
NSString * str = [NSString stringWithFormat:@"%d/%lu",i,(unsigned long)_picArr.count];
//label的颜色
label.textColor = [UIColor greenColor];
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:str];
NSRange redRange = NSMakeRange(0, [[noteStr string] rangeOfString:@"/"].location);
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
[label setAttributedText:noteStr];
最终样式: 1/4 2/4 等等
23.设置pch文件路径;
设置pch文件路径
$(SRCROOT)/$(PROJECT_NAME)/PrefixHeader.pch
24.iOS开发中,压缩图片的方法(2种方式);
iOS开发中,压缩图片的方法(2种方式)
方法一:
//压缩图片
-(UIImage*)imageWithImageSimple:(UIImage*)images scaledToSize:(CGSize)newSize{
UIGraphicsBeginImageContext(newSize);
[images drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
方法二:
//压缩图片
-(UIImage *)thumbnailFromImage:(UIImage*)image{
CGSize originImageSize = image.size;
CGRect newRect = CGRectMake(0, 0, 100, 100);
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
//(原图的宽高做分母,导致大的结果比例更小,做MAX后,ratio*原图长宽得到的值最小是40,最大则比40大,这样的好处是可以让原图在画进40*40的缩略矩形画布时,origin可以取=(缩略矩形长宽减原图长宽*ratio)/2 ,这样可以得到一个可能包含负数的origin,结合缩放的原图长宽size之后,最终原图缩小后的缩略图中央刚好可以对准缩略矩形画布中央)
float rotio = MAX(newRect.size.width/originImageSize.width, newRect.size.height/originImageSize.height);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:5.0];
//剪裁上下文
[path addClip];
//让image在缩略图居中()
CGRect projectRect;
projectRect.size.width = originImageSize.width* rotio;
projectRect.size.height = originImageSize.height * rotio;
projectRect.origin.x= (newRect.size.width- projectRect.size.width) /2;
projectRect.origin.y= (newRect.size.height- projectRect.size.height) /2;
//在上下文画图
[image drawInRect:projectRect];
UIImage *thumnailImg = UIGraphicsGetImageFromCurrentImageContext();
//结束绘制图
UIGraphicsEndImageContext();
return thumnailImg;
}
25.根据内容更改cell的高度;
根据内容更改cell的高度
方法一:
ChatModel *model = _dataArr[indexPath.row];
NSString *content = model.content;
CGSize size = [content boundingRectWithSize:CGSizeMake(200, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}context:nil].size;
return size.height + 30;
方法二:
/* 设置UILabel的高度 */
- (CGSize)sizeWithString:(NSString *)string size:(CGSize)size andFont:(int)font{
//限制最大的宽度和高度
CGRect rect = [string boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font]}context:nil];
return rect.size;
}
26.解决self对象出现循环引用问题;
__weak typeof (self)weakSelf = self;
为了解决self对象出现循环引用问题,在硬件操作中经常出现最常见的使用场景,在一个block内部,对当前对应的强引用属性操作时,容易出现循环引用的问题,需要使用以上代码修饰在block内部,使用weakSelf替代self,weakSelf在block内部就变成了弱引用,在block外,不影响self的使用,代码正常写即可.
self在block内部使用时,用weakSelf替换
__weak typeof(self)weakSelf = self;
27.更改UIAlertController中的message和title的文字对齐方式;
更改UIAlertController中的message和title的文字对齐方式:
UIView *subView1 = alert.view.subviews[0];
UIView *subView2 = subView1.subviews[0];
UIView *subView3 = subView2.subviews[0];
UIView *subView4 = subView3.subviews[0];
UIView *subView5 = subView4.subviews[0];
//取title和message:
UILabel *title = subView5.subviews[0];
UILabel *message = subView5.subviews[1];
//然后设置message内容居左:
message.textAlignment = NSTextAlignmentLeft;
title.textAlignment = NSTextAlignmentLeft;
28.根据版本号使用对应的方法;
根据版本号使用对应的方法
判断iOS 8.0 以下的方法如下:
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
#endif
判断iOS 8.0 以上的方法如下:
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0
#endif
29.iOS 内购的流程如下;
iOS 内购的流程如下
1. 程序向服务器发送请求,获得一份产品列表。
2. 服务器返回包含产品标识符的列表。
3. 程序向App Store发送请求,得到产品的信息。
4. App Store返回产品信息。
5. 程序把返回的产品信息显示给用户(App的store界面)
6. 用户选择某个产品
7. 程序向App Store发送支付请求
8. App Store处理支付请求并返回交易完成信息。
9. 程序从信息中获得数据,并发送至服务器。
10. 服务器纪录数据,并进行审(我们的)查。
11. 服务器将数据发给App Store来验证该交易的有效性。
12. App Store对收到的数据进行解析,返回该数据和说明其是否有效的标识。
13. 服务器读取返回的数据,确定用户购买的内容。
14. 服务器将购买的内容传递给程序。
30.iOS开发中,系统自带的函数;
iOS开发中,系统自带的函数
round:如果参数是小数,则求本身的四舍五入。
ceil:如果参数是小数,则求最小的整数但不小于本身.
floor:如果参数是小数,则求最大的整数但不大于本身.
31.避免同一界面里的两个UIButton同时被选中,触发action事件;
避免同一界面里的两个UIButton同时被选中,触发action事件
button.exclusiveTouch = YES;
32.模仿请求数据,延迟2s加载数据;
//模仿请求数据,延迟2s加载数据
[self performSelector:@selector(loadData) withObject:nil afterDelay:2];
33.监听手机横竖屏;
//注册旋转屏幕的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
//为了适配横竖屏
float padding1 = HitoSafeAreaHeight;
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(self.view);
make.left.mas_equalTo(self.view);
make.right.mas_equalTo(self.view);
make.bottom.mas_equalTo(self.view).offset(-padding1);
}];
34.控制台打印一些乱七八糟的东西;
控制台打印一些乱七八糟的东西,解决办法:
如果没有OS_ACTIVITY_MODE字段,添加该字段,如果该字段存在,就设置Value值为disable,并且打钩,最后Close即可.
35.UITextField PlaceHolder居中显示问题;
// UITextField PlaceHolder居中显示问题;
if (_phoneTextField == nil) {
_phoneTextField = [[QDDLTextField alloc] initWithFrame:CGRectZero leftView:nil inset:KWFloat(30)];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.alignment = NSTextAlignmentCenter;
NSAttributedString *attri = [[NSAttributedString alloc] initWithString:@"请填写手机号" attributes:@{NSForegroundColorAttributeName:QDDCOLOR(163, 163, 163, 1),NSFontAttributeName:[UIFont qdd_fontOfSize:34], NSParagraphStyleAttributeName:style}];
_phoneTextField.attributedPlaceholder = attri;
_phoneTextField.layer.borderColor = QDDCOLOR(221, 221, 221, 1).CGColor;
_phoneTextField.layer.borderWidth = 1;
_phoneTextField.layer.cornerRadius = 2;
_phoneTextField.keyboardType = UIKeyboardTypePhonePad;
}
return _phoneTextField;
36.手机号码验证,身份证验证,邮箱验证;
/*手机号码验证 MODIFIED BY HELENSONG*/
+(BOOL) isValidateMobile:(NSString *)mobile
{
//手机号以13, 15,18开头,八个 \d 数字字符
//NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
NSString *phoneRegex = @"^(0|86|17951)?(13|15|17|18|14)[0-9]{9}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
// NSLog(@"phoneTest is %@",phoneTest);
return [phoneTest evaluateWithObject:mobile];
}
/*身份证 MODIFIED BY HELENSONG*/
+(BOOL) isValidateIndCard:(NSString *)mobile{
//手机号以13, 15,18开头,八个 \d 数字字符
//NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
NSString *phoneRegex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
// NSLog(@"phoneTest is %@",phoneTest);
return [phoneTest evaluateWithObject:mobile];
}
/*邮箱验证 MODIFIED BY HELENSONG*/
+(BOOL)isEmailAddress:(NSString *)nickname{
NSString *emailRegex = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
// NSLog(@"phoneTest is %@",phoneTest);
return [phoneTest evaluateWithObject:nickname];
}
37.实现多次按钮被点击;
// 防止按钮多次被点击
- (IBAction)servicePhoneBtnClick:(UIButton *)sender {
self.servicePhoneBtn.enabled = NO;
//实现的功能
[self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:1.0f];
}
-(void)changeButtonStatus
{
self.servicePhoneBtn.enabled = YES;
}
38.随机颜色;
// 随机颜色
#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]
#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))
39.获取app当前ViewController;
#pragma mark 获取app当前ViewController
- (UIViewController *)topViewController {
UIViewController *resultVC;
resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
while (resultVC.presentedViewController) {
resultVC = [self _topViewController:resultVC.presentedViewController];
}
return resultVC;
}
- (UIViewController *)_topViewController:(UIViewController *)vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self _topViewController:[(UINavigationController *)vc topViewController]];
} else if ([vc isKindOfClass:[UITabBarController class]]) {
return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
} else {
return vc;
}
return nil;
}
40.获取View所在的Viewcontroller方法;
//获取View所在的Viewcontroller方法
- (UIViewController *)viewController {
for (UIView* next = [self superview]; next; next = next.superview) {
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
41.归档和解档;
//归档
NSString *temp = NSTemporaryDirectory();
NSString *filePath = [temp stringByAppendingPathComponent:@"objc.data"];
//注:保存文件的扩展名可以任意取,不影响。
//NSLog(@"%@", filePath);
[NSKeyedArchiver archiveRootObject:params toFile:filePath];
//解档
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"objc.data"];
NSMutableDictionary *params = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
42.实时获取键盘的高度;
//实时获取键盘的高度
//添加通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height;
}
43.设置TextView placeHolder方法;
// 设置TextView placeHolder方法
- (void)setplaceholderLabel:(NSString *)placeLabel andTextView:(UITextView *)textView{
// _placeholderLabel
UILabel *placeHolderLabel = [[UILabel alloc] init];
placeHolderLabel.text = placeLabel;
placeHolderLabel.numberOfLines = 0;
placeHolderLabel.textColor = [UIColor lightGrayColor];
[placeHolderLabel sizeToFit];
[textView addSubview:placeHolderLabel];
// same font
textView.font = [UIFont systemFontOfSize:14.f];
placeHolderLabel.font = [UIFont systemFontOfSize:14.f];
[textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
}
44.计算文字占据的高度;
- (float)getContactHeight:(NSString*)contact{
NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
CGSize maxSize = CGSizeMake(MainScreenWidth - 24, MAXFLOAT);
// 计算文字占据的高度
CGSize size = [contact boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
return size.height;
}
45.ios修改textField的placeholder的字体颜色、大小;
ios修改textField的placeholder的字体颜色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
//更改文本输入框占位符文字的颜色
[_lastText setValue:[UIColor colorWithRed:192/255.0 green:192/255.0 blue:192/255.0 alpha:0.3] forKeyPath:@"_placeholderLabel.textColor"];
//更改文本输入框占位符文字的大小
[_lastText setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font”];
46.限制UITextField的最大输入字符数;
限制UITextField的最大输入字符数;
#define Max_Count 7
//监听UITextFieldTextDidChangeNotification通知,可以在UITextField发生变化的时候接收到通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged) name:@"UITextFieldTextDidChangeNotification" object:nil];
//实现监听方法
-(void)textFiledEditChanged{
NSString *toBeString = self.goodsNameTF.text;
// 键盘输入模式
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
if ([lang isEqualToString:@"zh-Hans"]) {
// 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [self.goodsNameTF markedTextRange];
//获取高亮部分的从range.start位置开始,向右偏移0所得的字符所在的位置。
//如果高亮部分不存在,那么就返回nil,反之就不是nil
UITextPosition *position = [self.goodsNameTF positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > Max_Count) {
self.goodsNameTF.text = [toBeString substringToIndex:Max_Count];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
// 中文输入法以外的直接对其统计限制即可
else{
if (toBeString.length > Max_Count) {
self.goodsNameTF.text = [toBeString substringToIndex:Max_Count];
}
}
}