# Masonry 显示fream
// 先调用superView的layoutIfNeeded方法再获取frame
[self.view layoutIfNeeded];
# 苹果开发者账号,支付失败问题解决 开户行手机号 公司邮箱 开户行地址
CocoPods的错误
cocopodes 使用
1.使用CocoaPods
打开终端,使用cd命令定位到需要使用CocoaPods的项目根路径。如:
cd+空格 然后把文件拖进命令行
2.然后在通过search命令来查找库的信息,如需要加入JSONKit,那可以如下写法:
pod search AFNetworking
3.得到必要的库信息后,现在需要在项目中建立Podfile文件。通过下面的命令:
touch Podfile
然后编辑Podfile文件,命令如下:
open -e Podfile
在弹出的编辑界面中输入下面内容:
platform :ios pod
然后调用下面命令来进行初始化:
pod install
如果Podfile中添加了新库,可以使用下面命令进行更新:
pod update
# Git
首先下载创建的git
cd 文件目录
1.git add . (添加所有修改)
2.git status
3.git commit -m '修改的内容'
4.git push origin master
# Uncomment this line to define a global platform for your project
# unrecognized selector sent to class 阿里云上传问题
$(SRCROOT)/Haoqinsheng02/UIFrames/Vendors/aliyunOSS/AliyunOSSiOS.framework/AliyunOSSiOS -force_load
-ObjC
这个flag告诉链接器把库中定义的Objective-C类和Category类都加载进来。但是如果静态库中有类和category的话只有加入这个flag才行。
-all_load
用了-ObjC以后,如果类库中只有category没有Objective-C类的时候这些category还是加载不进来。变通方法就是加入-all_load或者-force-load。-all_load会强制链接器把目标文件都加载进来,即使没有objc代码
-force_load
这个flag所做的事情跟-all_load其实是一样的,只是-force_load需要指定要进行全部加载的库文件的路径,这样的话,你就只是完全加载了一个库文件,不影响其余库文件的按需加载
# CocoPods的应用
$ touch Podfile
platform :ios, '9.0'
use_frameworks!
target '工程名称' do
pod 'MJRefresh'
pod 'MBProgressHUD'
pod 'Masonry'
end
3.$ pod install
4.$ pod update
platform :ios, '9.0'
use_frameworks!
target '你的工程的名字' do
pod 'MJRefresh'
pod 'MBProgressHUD'
pod 'Masonry'
end
\
# 隐藏导航栏
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
# 隐藏底部状态栏
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
# 2.Masonry 使用
MasonyBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.view addSubview:btn];
必须先添加到父控件内再进行约束
[MasonyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(backView.mas_bottom).offset(30);
make.left.mas_equalTo(backView.mas_left).mas_offset(10);
make.height.mas_equalTo(30);
make.right.equalTo(backView.mas_right).mas_offset(-10);
}];
# 3. AFNetworking进行网络请求,多任务异步请求
我们知道使用AFNetworking进行网络请求,都是异步的,有时候我们需要等若干个无序的(2个或者更多个)异步请求都成功后再执行某些代码,当遇到这种需求的时候,最简单的做法,或者说我们一般会采用的做法是,将一个异步请求嵌套在另一个异步请求中,就是在第一个请求成功返回后再调用第2个异步请求,这种做法其实是不太好的,既浪费了时间
#如何使用dispatch group来实现上述场景中的需求
1.创建dispatch_group_t
```objc
dispatch_group_t group = dispatch_group_create();
```
2.使用dispatch_group_enter进入group,表示任务开始
```objc
dispatch_group_enter(group);
```
3.使用dispatch_group_leave退出group,表示任务完成
```objc
dispatch_group_leave(group);
```
4.使用dispatch_group_notify注册group里所有任务完成后的回调block
```objc
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
});
```
注:与dispatch_group_notify对应的还有一个叫dispatch_group_wait的东西,这2者的区别是:
dispatch_group_notify:是异步的,不阻塞当前线程
dispatch_group_wait:会阻塞当前线程,直到dispatch group中所有任务都完成才返回
完整的调用代码:
-(void)groupSync
{
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(5);
NSLog(@"任务一完成");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(8);
NSLog(@"任务二完成");
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务完成");
});
}
# 异步执行代码
//1.获得全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2.添加任务到队列中,就可以执行任务
//异步函数:具备开启新线程的能力
dispatch_async(queue, ^{
NSLog(@"下载图片1----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下载图片2----%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"下载图片2----%@",[NSThread currentThread]);
});
//打印主线程
NSLog(@"主线程----%@",[NSThread mainThread]);
# 获取图片尺寸
-(UIImage *)rescaleImageToSize:(CGSize)size {
CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
[self drawInRect:rect]; // scales image to rect
UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resImage;
}
# 3.通知获取
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:SVProgressHUDWillAppearNotification
object:nil];
# 4.UItableviewcell取消选中
self.selectionStyle=UITableViewCellSelectionStyleNone;
# 5设置tableViewCell间的分割线的颜色
[TableView setSeparatorColor:[UIColor xxxx ]];
设置_tableView数据比较少的时候,下面显示的是白色
[self setExtraCellLineHidden:_tableView];
-(void)setExtraCellLineHidden: (UITableView *)tableView
{
UIView *viewback = [UIView new];
viewback.backgroundColor = [UIColor clearColor];
[_myTableview setTableFooterView:viewback];
}
# 6 从nib中加载cell
[self.regittableview registerNib:[UINib nibWithNibName:@"RegisterCell" bundle:nil] forCellReuseIdentifier:@"register"];
tableView cell选中颜色
cell内部设置
[self setBackgroundColor:[UIColor redColor]];
self.selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];
self.selectedBackgroundView.backgroundColor =UIColorFromRGB(0xFFEAEA);
# 7.iOS开发之下拉崩溃"index ? beyond bounds for empty array"
当下拉tableview时,当超过一定距离时,最下方的cell肯定会超出tableview显示范围,然后在下拉弹回时,会调用- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法。
如果在下拉动作中将arr清空,那么在tableview弹回调用此方法时,cell需要从arr中取值,此时会崩溃。
解决:
网络请求成功之后再清空数据源,然后再给数据源赋值,再去reload.
# 左滑删除
IOS UITableViewUITableView小技巧--实现cell向左滑动删除,编辑等功能
//这里是选择哪个cell可以被删除
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"点击了删除");
}];
UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NSLog(@"点击了编辑");
}];
editAction.backgroundColor = [UIColor grayColor];
return @[deleteAction, editAction];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
editingStyle = UITableViewCellEditingStyleDelete;
}
# 当前时间
+(NSString*)getCurrentTimes{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//现在时间,你可以输出来看下是什么格式
NSDate *datenow = [NSDate date];
//----------将nsdate按formatter格式转成nsstring
NSString *currentTimeString = [formatter stringFromDate:datenow];
NSLog(@"currentTimeString = %@",currentTimeString);
return currentTimeString;
}
富文本
NSAttributedString *stringmoey = [[NSAttributedString alloc] initWithString:moneyStr attributes:@{
//字体宽度NSKernAttributeName : [NSNumber numberWithInt:3],
NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),
//底部横线
NSUnderlineColorAttributeName:[UIColor redColor],
//字体颜色
NSForegroundColorAttributeName:[UIColor redColor]}];
NSAttributedString *stringyonghu = [[NSAttributedString alloc] initWithString:@"元到该用户支付宝" ];
[mutableAttriteStr appendAttributedString:stringmoey];
[mutableAttriteStr appendAttributedString:stringyonghu];
_ShowMoneylabel.attributedText =mutableAttriteStr;
# 拼接字体颜色
-(NSMutableAttributedString*)passString:(NSString*)stringone withSting:(NSString*)secondStr withStringThree:(NSString*)threething{
NSMutableAttributedString *mutableAttriteStr = [[NSMutableAttributedString alloc] initWithString:stringone];
NSAttributedString *stringmoey = [[NSAttributedString alloc] initWithString:secondStr attributes:@{
//字体宽度NSKernAttributeName : [NSNumber numberWithInt:3],
NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),
//底部横线
NSUnderlineColorAttributeName:[UIColor redColor],
//字体颜色
NSForegroundColorAttributeName:[UIColor redColor]}];
NSAttributedString *stringyonghu = [[NSAttributedString alloc] initWithString:threething ];
[mutableAttriteStr appendAttributedString:stringmoey];
[mutableAttriteStr appendAttributedString:stringyonghu];
return mutableAttriteStr;
}
/**
# 开始到结束的时间差
*/
-(NSString *)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startD =[date dateFromString:startTime];
NSDate *endD = [date dateFromString:endTime];
NSTimeInterval start = [startD timeIntervalSince1970]*1;
NSTimeInterval end = [endD timeIntervalSince1970]*1;
NSTimeInterval value = end - start;
int second = (int)value %60;//秒
int minute = (int)value /60%60;
int house = (int)value / (24 *3600)%3600;
int day = (int)value / (24 *3600);
NSString *str;
if (day != 0) {
str = [NSString stringWithFormat:@"耗时%d天%d小时%d分%d秒",day,house,minute,second];
}else if (day==0 && house !=0) {
str = [NSString stringWithFormat:@"耗时%d小时%d分%d秒",house,minute,second];
}else if (day==0 && house==0 && minute!=0) {
str = [NSString stringWithFormat:@"耗时%d分%d秒",minute,second];
}else{
str = [NSString stringWithFormat:@"耗时%d秒",second];
}
return str;
}
//获取当前时间日期
NSDate *date=[NSDate date];
NSDateFormatter *format1=[[NSDateFormatter alloc] init];
[format1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *dateStr;
dateStr=[format1 stringFromDate:date];
NSLog(@"%@",dateStr);
# 将array数组转换为string字符串
NSString *str = [array componentsJoinedByString:@","];--分隔符
# 分隔字符串
NSString *string = Zan_number;
NSArray *array1 = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"::::::"]];
NSLog(@"%@",array1[ 0 ] );
_ZanNumberlabel.text = array1[0];
# 根据字符串截取数组
NSString * str_pic =[NSString stringWithFormat:@"%@",model.cover];
NSArray *array = [str_pic componentsSeparatedByString:@","];
# xib 修改return键盘为 done
收起键盘:通过UITextFieldDelegate协议监听键盘的return按钮时都被点击收回键盘。
我们按住Commond键点击returnKeyType,进去会看到returnKeyType是一个枚举类型,也就是键盘上的返回按钮的类型。
typedef NS_ENUM(NSInteger, UIReturnKeyType) {
UIReturnKeyDefault,
UIReturnKeyGo,
UIReturnKeyGoogle,
UIReturnKeyJoin,
UIReturnKeyNext,
UIReturnKeyRoute,
UIReturnKeySearch,
UIReturnKeySend,
UIReturnKeyYahoo,
UIReturnKeyDone,
UIReturnKeyEmergencyCall,
UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
};
这里的returnKeyType设置类型,只会影响键盘上turnkey位置将显示的文字,如UIReturnKeyDefault显示“换行”,UIReturnKeyGo显示“前往”,UIReturnKeyGoogle显示“搜索”,UIReturnKeyDone显示“完成”。而它的实际点击效果需要在UITextFieldDelegate的代理方法里面去实现。这里需要实现的是如下方法:
-(BOOL)textFieldShouldReturn:(UITextField *)textField;
具体实现方法如下:
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[_testField resignFirstResponder];
return YES;
}
# pagecontroller的设置
_pageControl = [[UIPageControl alloc] init];
[_viewbotomscroll addSubview:_pageControl];
// _pageControl.frame = CGRectMake(210, 235, 20, 20);//指定位置大小
_pageControl.numberOfPages = count;//指定页面个数
_pageControl.currentPage = 0;//指定pagecontroll的值,默认选中的小白点(第一个)
//添加委托方法,当点击小白点就执行此方法
_pageControl.pageIndicatorTintColor = [UIColor grayColor];// 设置非选中页的圆点颜色
_pageControl.currentPageIndicatorTintColor = [UIColor redColor]; // 设置选中页的圆点颜色
[_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(@-54);
make.centerX.equalTo(_viewbotomscroll);
make.width.height.equalTo(@20);
}];
# 切四个角
1.如果是切四个角的圆角,代码示例:
self.picImage.layer.cornerRadius = 8;
self.picImage.layer.masksToBounds = YES;
# 切两个角
2.如果是四个角中的某几个角,一个,两个,或者3个,代码示例(切的左下,和右下):
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.tipLabel.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = _tipLabel.bounds;
maskLayer.path = maskPath.CGPath;
self.tipLabel.layer.mask = maskLayer;
# runtime
Build Settings 搜索 msg Enable Strict Check of objc 改为NO 不允许检测是否使用底层库
方法欺骗
例子实在一个分类中
//改变连个方法的class
自己调自己 将自己的方法修改为系统 系统的方法改为自己
// method_exchangeImplementations(<#Method _Nonnull m1#>, <#Method _Nonnull m2#>)
//获取类方法
//class_getClassMethod(<#Class _Nullable __unsafe_unretained cls#>, <#SEL _Nonnull name#>)
//获取对象方法
// class_getInstanceMethod(<#Class _Nullable __unsafe_unretained cls#>, <#SEL _Nonnull name#>)
# kvo 底层实现
创建一个字类 nskvoNotitying_类 重写set方法
# 枚举类型
typedef enum : NSUInteger{
IsThem,
IsActive,
isHistory,
}Is_ThemeOrActive;
@property(nonatomic,assign)Is_ThemeOrActive themoractive;
# 字典转模型
.m 内的数据处理 不处理闪退
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
-(id)valueForUndefinedKey:(NSString *)key
{
return nil;
}
//有些属性 为空了我后续用到经常会崩溃 下面这个方法把<null>转为空字符串
-(void)setValuesForKeysWithDictionary:(NSDictionary<NSString *,id> *)keyedValues
{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:keyedValues];
NSArray *valueArray= [dic allKeys];
for (NSString *key in valueArray) {
if ([[dic objectForKey:key]isEqual:[NSNull null]]) {
[dic setObject:@" " forKey:key];
}
}
[super setValuesForKeysWithDictionary:dic];
}
# 字典转模型属性声明简单
-(void)propertyCodeWithDictionary:(NSDictionary *)dict
{
NSMutableString *strM = [NSMutableString string];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *str;
NSLog(@"%@",[obj class]);
if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")] || [obj isKindOfClass:NSClassFromString(@"NSTaggedPointerString")] || [obj isKindOfClass:NSClassFromString(@"__NSCFConstantString")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSArray *%@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSDictionary *%@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
}
[strM appendFormat:@"\n%@\n",str];
}];
NSLog(@"%@",strM);
}
# xib 高度自适应 iOS8 以后
从nib中加载cell
[self.tableview registerNib:[UINib nibWithNibName:@"HaiXuanCommentCell" bundle:nil] forCellReuseIdentifier:@"haixuancomment"];
self.tableview.rowHeight = UITableViewAutomaticDimension;//设置cell的高度为自动计算,只有才xib或者storyboard上自定义的cell才会生效,而且需要设置好约束
self.tableview.estimatedRowHeight = 280;//必须设置好预估值
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
self.tableview.rowHeight = UITableViewAutomaticDimension;
self.tableview.estimatedRowHeight = 280;
return self.tableview.rowHeight;
}
# 沙箱环境
# 字典拼接数据
NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
NSDictionary *dicpremdicer = [userDefaultes objectForKey:@"Allrequest"];
NSMutableDictionary * myHeader = [[NSMutableDictionary alloc] init];
[myHeader setValue:VideoId forKey:@"videoID"];
[myHeader addEntriesFromDictionary:dicpremdicer];
# 限制输入字符
#pragma mark -限制病情描述输入字数(最多不超过25个字)
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
//不支持系统表情的输入
if ([[textView textInputMode] primaryLanguage]==nil||[[[textView textInputMode] primaryLanguage]isEqualToString:@"emoji"]) {
return NO;
}
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//获取高亮部分内容
//NSString * selectedtext = [textView textInRange:selectedRange];
//如果有高亮且当前字数开始位置小于最大限制时允许输入
if (selectedRange && pos) {
NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
NSRange offsetRange =NSMakeRange(startOffset, endOffset - startOffset);
if (offsetRange.location < MAX_LIMIT_NUMS) {
return YES;
}else{
return NO;
}
}
NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
NSInteger caninputlen =MAX_LIMIT_NUMS - comcatstr.length;
if (caninputlen >=0){
return YES;
}else{
NSInteger len = text.length + caninputlen;
//防止当text.length + caninputlen < 0时,使得rg.length为一个非法最大正数出错
NSRange rg = {0,MAX(len,0)};
if (rg.length >0){
NSString*s =@"";
//判断是否只普通的字符或asc码(对于中文和表情返回NO)
BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
if (asc) {
s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
}else{
__block NSInteger idx =0;
__block NSString *trimString =@"";//截取出的字串
//使用字符串遍历,这个方法能准确知道每个emoji是占一个unicode还是两个
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock: ^(NSString* substring,NSRange substringRange,NSRange enclosingRange,BOOL*stop) {
if (idx >= rg.length) {
*stop =YES;//取出所需要就break,提高效率
return ;
}
trimString = [trimString stringByAppendingString:substring];
idx++;
}];
s = trimString;
}
//rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
[textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
//既然是超出部分截取了,哪一定是最大限制了。
self.Label_show_number.text = [NSString stringWithFormat:@"%d/%ld",0,(long)MAX_LIMIT_NUMS];
}
return NO;
}
}
#pragma mark -显示当前可输入字数/总字数
-(void)textViewDidChange:(UITextView *)textView{
UITextRange *selectedRange = [textView markedTextRange];
//获取高亮部分
UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
//如果在变化中是高亮部分在变,就不要计算字符了
if (selectedRange && pos) {
return;
}
NSString *nsTextContent = textView.text;
NSInteger existTextNum = nsTextContent.length;
if (existTextNum >MAX_LIMIT_NUMS){
//截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
[textView setText:s];
}
//不让显示负数
self.Label_show_number.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,MAX_LIMIT_NUMS - existTextNum),MAX_LIMIT_NUMS];
}
# 加载XIB VIEW
CustomView *view = [[NSBundle mainBundle]loadNibNamed:@"xib的名字" owner:self options:nil].lastObject;
# xib 切圆角
layer.cornerRadius
layer.masksToBounds
layer.borderWidth ,注意该 key 对应 Value 的 type 应该设置为 String/Number 两种类型均可
layer.borderColor , 注意该 key 对应 Value 的 type 应该设置为Color
# navigationController 按钮自定义
-(void)configurerightNav{
UIView *shareNavleftView = [[UIView alloc] init];
shareNavleftView.frame = CGRectMake(0.0, 0.0, 191.0, 40.0);
UIButton * label_release =[[UIButton alloc]init];
[label_release setTitle:@"发布" forState:UIControlStateNormal];
label_release.titleLabel.textAlignment = NSTextAlignmentCenter;
label_release.titleLabel.textColor = UIColorFromRGB(0xFFF24C52);
label_release.titleLabel.font = Font(12);
label_release.layer.borderColor=RGBCOLOR(241, 76, 82).CGColor;
label_release.layer.borderWidth=1;
label_release.layer.cornerRadius = 15;
label_release.layer.masksToBounds = YES ;
label_release.frame = CGRectMake(120, 10, 50, 30);
[shareNavleftView addSubview:label_release];
[label_release addTarget:self action:@selector(rightBarButtonItemClick:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:shareNavleftView];
}
# cell 选中的自定义
-(void)awakeFromNib {
[super awakeFromNib];
// Initialization code
UIButton *accessBtn = [[UIButton alloc] init];
accessBtn.frame = CGRectMake(0, 0, 15/2.0, 13);
[accessBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
[accessBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateHighlighted];
self.accessoryView = accessBtn;
}
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
if (highlighted == YES) {
((UIButton *)self.accessoryView).highlighted = YES;
}else{
((UIButton *)self.accessoryView).highlighted = NO;
}
[super setHighlighted:highlighted animated:animated];
}
# EXC_BAD_ACCESS(code=1问题的解决办法
属性申明错误 检查
__NSCFNumber isEqualToString:的问题.--[__NSCFNumber isEqualToString:]: unrecognized selector sent to in
-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x7c2680b0
解析服务器返回的状态码,如果直接跟字符串对比的话,会出现这个错误。网上说将isEqualToString改成isEqual,果然不报错了,但是匹配返回的布尔值跟预期的不一样。
果断将得到数据,再次用nsstring包装下,然后还是用isEqualToString来进行匹配,答案是正确的。
# 编译报错
error: couldn't remove '/Users/mobilewise/Library/Developer/Xcode/DerivedData/MCDM-epoyegaizqaljifbmfuxvovvwxqn/Build/Products/Debug-iphoneos/TencentOpenApi_IOS_Bundle.bundle' after command failed: Directory not empty
Build Phases--->>Copy Bundle Resources,删除TencentOpenApi_IOS_Bundle.bundle
# html innerHTML 属性设置或返回表格行的开始和结束标签之间的 HTML
document.getElementById("tr2").innerHTML(获取标签中的数据)
document.getElementById("demo").innerHTML="点击以后切换成我输入的东西";
document.write() 向文档输出写内容
控制台输出
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
JavaScript 拥有动态类型。这意味着相同的变量可用作不同的类型
# script 数组字典(对象)
<script>
var person=
{
name : "John",
like : "singing",
id : 5566
};
var nameArray =["0","d","f"];
document.write(person.id + "<br>");
document.write(person["name"] + "<br>");
document.write(person.like+"<br>");
document.write(nameArray[0] + "<br>");
for(let index in nameArray){
document.write(nameArray[index]+ "<br>")
}
for (let x in nameArray)
{
document.write(nameArray[x] + "<br />")
}
</script>s
# 判断图片是否有内容
UIImage *image = [UIImage imageNamed:@""];
CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];
if (cim == nil && cgref == NULL)
{
NSLog(@"no image");
} else {
NSLog(@"imageView has a image");
}
---------------------
# 加载html
UIWebView * webview =[[UIWebView alloc]initWithFrame:self.view.bounds];
webview.delegate=self;
[self.view addSubview:webview];
NSString *content = [_strsaxy stringByReplacingOccurrencesOfString:@"&quot" withString:@"'"];
content = [content stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
content = [content stringByReplacingOccurrencesOfString:@">" withString:@">"];
content = [content stringByReplacingOccurrencesOfString:@""" withString:@"\""];
NSString *htmls = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" /> \n"
"<style type=\"text/css\"> \n"
"body {font-size:15px;}\n"
"</style> \n"
"</head> \n"
"<body>"
"<script type='text/javascript'>"
"window.onload = function(){\n"
"var $img = document.getElementsByTagName('img');\n"
"for(var p in $img){\n"
" $img[p].style.width = '100%%';\n"
"$img[p].style.height ='auto'\n"
"}\n"
"}"
"</script>%@"
"</body>"
"</html>",content];
webview.delegate = self;
[webview loadHTMLString:htmls baseURL:nil];
# 字符串特殊符号判断
if ([model.cover rangeOfString:@","].location != NSNotFound) {
// NSLog(@"含有这种符号!");
NSString *string =[NSString stringWithFormat:@"%@", model.cover];
NSArray *array1 = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
string_image = array1.firstObject;
}else{
string_image = model.cover;
}
# tableView 刷新数据来回跳
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
数据做处理
# block声明
/**
* 类型自定义 传值页面
*/
typedef void (^ReturnValueBlock) (NSString *strValue);
@interface WebviewVC : UIViewController
/**
* 声明一个ReturnValueBlock属性,这个Block是获取传值的界面传进来的
*/
@property(nonatomic, copy) ReturnValueBlock returnValueBlock;
__weak typeof(self) weakself = self;
if (weakself.returnValueBlock) {
//将自己的值传出去,完成传值
weakself.returnValueBlock([NSString stringWithFormat:@"逆向传回数字"]);
}
/** 收到值的页面 */
self.returnValueBlock = ^(NSString *strValue) {
responseCallback(strValue);
};
# 键盘高度设定
#pragma mark - 键盘通知
-(void)addNoticeForKeyboard {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
//键盘farme值
-(void)keyboardFrameChange:(NSNotification *)notifi{
NSDictionary *userInfo = notifi.userInfo;
CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
void(^animations)(void) = ^{
[self willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
};
void(^completion)(BOOL) = ^(BOOL finished){
};
[UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:animations completion:completion];
}
-(void)willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame
{
if (toFrame.origin.y == [[UIScreen mainScreen] bounds].size.height){
//键盘收起
textViewCommen.frame = CGRectMake(10, Main_Screen_Height-40, Main_Screen_Width-80, 30);
commenBtn.frame = CGRectMake(MaxX(textViewCommen)+10, textViewCommen.frame.origin.y, 60, 30);
}else{
//键盘升起
CGFloat keyboardHeight = toFrame.size.height;
NSLog(@"%f",keyboardHeight);
textViewCommen.frame = CGRectMake(10, Main_Screen_Height-30-keyboardHeight, Main_Screen_Width-80, 30);
commenBtn.frame = CGRectMake(MaxX(textViewCommen)+10, textViewCommen.frame.origin.y, 60, 30);
}
}
#tablevie 刷新以后滚到底部
[_HosTableview reloadData];
dispatch_async(dispatch_get_main_queue(), ^{
if(_HosTableview.contentSize.height>self.HosTableview.bounds.size.height){
[self.HosTableview setContentOffset:CGPointMake(0, self.HosTableview.contentSize.height-self.HosTableview.bounds.size.height)];
}
});
# 点九拉伸
-(UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
这个函数是UIImage的一个实例函数,它的功能是创建一个内容可拉伸,而边角不拉伸的图片,需要两个参数,第一个是左边不拉伸区域的宽度,第二个参数是上面不拉伸的高度。
# 获取主控制器
//获取主控制器
-(UIViewController *)findCurrentViewController
{
UIWindow *window = [[UIApplication sharedApplication].delegate window];
UIViewController *topViewController = [window rootViewController];
while (true) {
if (topViewController.presentedViewController) {
topViewController = topViewController.presentedViewController;
} else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
topViewController = [(UINavigationController *)topViewController topViewController];
} else if ([topViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tab = (UITabBarController *)topViewController;
topViewController = tab.selectedViewController;
} else {
break;
}
}
return topViewController;
}
UIViewController * controller= [self findCurrentViewController];
if ([controller isKindOfClass:[HostrsPublicViewController class]])
# 高度XY获取
CGRectGetHeight返回label本身的高度
CGRectGetMinY返回label顶部的坐标
CGRectGetMaxY 返回label底部的坐标
CGRectGetMinX 返回label左边缘的坐标
CGRectGetMaxX 返回label右边缘的坐标
CGRectGetMidX表示得到一个frame中心点的X坐标
CGRectGetMidY表示得到一个frame中心点的Y坐标
# 经常变换cell的点击
1.
self.viewControllers = @[@"ZFKeyboardViewController",
@"ZFNoramlViewController",
@"ZFTableHeaderViewController",
@"ZFNotAutoPlayViewController",
@"ZFAutoPlayerViewController",
@"ZFSmallPlayViewController",
@"ZFLightTableViewController",
@"ZFMixViewController",
@"ZFDouYinViewController",
@"ZFCollectionViewController",
@"ZFHorizontalCollectionViewController",
@"ZFCollectionViewListController",
@"ZFFullScreenViewController"];
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *vcString = self.viewControllers[indexPath.row];
UIViewController *viewController = [[NSClassFromString(vcString) alloc] init];
if ([vcString isEqualToString:@"ZFDouYinViewController"]) {
[(ZFDouYinViewController *)viewController playTheIndex:0];
}
viewController.navigationItem.title = self.titles[indexPath.row];
if ([vcString isEqualToString:@"ZFFullScreenViewController"]) {
[self.navigationController pushViewController:viewController animated:NO];
} else {
[self.navigationController pushViewController:viewController animated:YES];
}
}
2.
-(void)viewDidLoad {
[super viewDidLoad];
self.title = @"✎ YYText Demo ✎";
self.titles = @[].mutableCopy;
self.classNames = @[].mutableCopy;
[self addCell:@"Text Attributes 1" class:@"YYTextAttributeExample"];
[self addCell:@"Text Attributes 2" class:@"YYTextTagExample"];
[self addCell:@"Text Attachments" class:@"YYTextAttachmentExample"];
[self addCell:@"Text Edit" class:@"YYTextEditExample"];
[self addCell:@"Text Parser (Markdown)" class:@"YYTextMarkdownExample"];
[self addCell:@"Text Parser (Emoticon)" class:@"YYTextEmoticonExample"];
[self addCell:@"Text Binding" class:@"YYTextBindingExample"];
[self addCell:@"Copy and Paste" class:@"YYTextCopyPasteExample"];
[self addCell:@"Undo and Redo" class:@"YYTextUndoRedoExample"];
[self addCell:@"Ruby Annotation" class:@"YYTextRubyExample"];
[self addCell:@"Async Display" class:@"YYTextAsyncExample"];
[self.tableView reloadData];
}
-(void)addCell:(NSString *)title class:(NSString *)className {
[self.titles addObject:title];
[self.classNames addObject:className];
}
#pragma mark - Table view data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _titles.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YY"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YY"];
}
cell.textLabel.text = _titles[indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *className = self.classNames[indexPath.row];
Class class = NSClassFromString(className);
if (class) {
UIViewController *ctrl = class.new;
ctrl.title = _titles[indexPath.row];
[self.navigationController pushViewController:ctrl animated:YES];
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
# cell连续点击问题处理
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (cellSelected) {
return;
}else{
cellSelected = YES;
[self performSelector:@selector(didSelectRowAtIndexPath:) withObject:indexPath];
//[self performSelector:@selector(didSelectRowAtIndexPath:) withObject:indexPath afterDelay:2.0]; // 延迟执行,不推荐
}
}
-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%ld",indexPath.row);
// 模拟事件处理,2秒之后再次响应
// do something
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
cellSelected = NO;
});
}
# A跳B跳A循环跳转
{
MusciStarDetialController *stardetialVC = [[MusciStarDetialController alloc]init];
NSString * modeluser_id =[NSString stringWithFormat:@"%@",_active_model.user_id];
stardetialVC.ID =modeluser_id;
NSString *role_id = [NSString stringWithFormat:@"%@",_active_model.role_id];
// stardetialVC.pass_role_id =role_id;
#pragma mark===== 跳转琴行
if ([role_id isEqualToString:registDome]||[role_id isEqualToString:VIPDom]||[role_id isEqualToString:CertificationDom]) {
ClassDetialController *classDetialVC = [[ClassDetialController alloc] init];
classDetialVC.store_id =modeluser_id ;
classDetialVC.ID = modeluser_id;
classDetialVC.pass_sceond_store_id = role_id;
self.navigationController.hidesBottomBarWhenPushed = YES;
NSMutableArray *pageArray = [self.navigationController.viewControllers mutableCopy];
static NSString * stingpass;
[pageArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[ClassDetialController class]]) {
stingpass = @"1";
}
}];
if ([stingpass isEqualToString:@"1"]) {
for (int i = 0; i<pageArray.count; i++) {
id vc = pageArray[i];
if ([vc isKindOfClass:[ClassDetialController class]]) {
[self.navigationController popToViewController:vc animated:NO];
}
}
}else{
[self.navigationController pushViewController:classDetialVC animated:YES];
}
}
}
# oc swift混编
一种系统自己创建桥接文件
2 file newfile headefile - objective-c Bridging Header 直接拖进去
桥接文件包含OC文件
OC的头文件 /*oc _ swift 需要包含这个头文件 项目名称-Swift.h*/
#import "IOStestOC-Swift.h"
#tableview 滚动到底部只第一次执行
1.-(void)viewDidLoad {
[super viewDidLoad];
self.scrollBottom = NO;
}
2. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (_scrollBottom == NO) { //只在初始化的时候执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.005 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (_HostiMutarray.count > 0) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([self.HosTableview numberOfRowsInSection:0]-1) inSection:0];
[self.HosTableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
});
}
return _HostiMutarray.count;
}
3. -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat height = scrollView.frame.size.height;
CGFloat contentOffsetY = scrollView.contentOffset.y;
CGFloat bottomOffset = scrollView.contentSize.height - contentOffsetY;
if (bottomOffset <= height)
{
//在最底部
}
else
{
if (_scrollBottom == NO) {
_scrollBottom = YES;
[self.HosTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_HostiMutarray count] - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}
}
# view 跳转 vc nav 跳转
// 取到tabbarcontroller
UITabBarController*tabBarController =(UITabBarController*) [UIApplication sharedApplication].keyWindow.rootViewController;
// 取到navigationcontroller
UINavigationController * nav = (UINavigationController *)tabBarController.selectedViewController;
[nav pushViewController:changevc animated:YES];
# tableview 下拉背景色
UIView *tableBackgroundView = [[UIView alloc]initWithFrame:self.squareTableview.bounds];
tableBackgroundView.backgroundColor = [UIColor whiteColor];
self.squareTableview.backgroundView = tableBackgroundView;
#NSDictionary使用中value遇到no summary如何判断为NULL
-(BOOL)isNull:(NSDictionary*)dict key:(NSString*)key{
if(![dict objectForKey:key]){
return NO;
}
id obj = [dict objectForKey:key];// judge NSNull
BOOL isNull = [obj isEqual:[NSNull null]];
return isNull;
}
#iOS生成图片
-(UIImage *)snapshotSingleView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#iOS 添加全屏遮盖图,能遮住navigationBar和tabBar
[[UIApplication sharedApplication].keyWindow addSubview:_view];
# 页面返回无效遍历视图栈的所有元素,找到目标视图,将目标视图创建新对象, 再使用popToViewController:animated:
for (UIViewController *vc in self.navigationController.childViewControllers) {
if ([vc isKindOfClass:[AViewController class]]) {
AViewController *mainVC = (AViewController *)vc;
[self.navigationController popToViewController:mainVC animated:YES];
}
}
# 图片裁剪适配
-(void)passChangemodel:(NSURL*)model_url{
[[SDWebImageDownloader sharedDownloader]downloadImageWithURL:model_url options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
if (!error && image) {
UIImage * CutImage = [self cutImage:image];
self.imagecover.image = CutImage;
}else {
self.imagecover.image = [UIImage imageNamed:@"3e0ae031690a4e77b64a0bc2f7d5033.jpg"];
}
}];
}
-(UIImage*)cutImage:(UIImage*)image{//压缩图片
CGSize newSize;CGImageRef imageRef = nil;
if ((image.size.width / image.size.height) < (_imagecover.size.width / _imagecover.size.height)) {
newSize.width = image.size.width;newSize.height = image.size.width * _imagecover.size.height / _imagecover.size.width;imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
} else {
newSize.height = image.size.height;newSize.width = image.size.height * _imagecover.size.width / _imagecover.size.height;imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));}
return [UIImage imageWithCGImage:imageRef];
}
# 底部导航条遮挡文字
_squareTableview.contentInset = UIEdgeInsetsMake(0, 0, self.tabBarController.tabBar.frame.size.height, 0);
# collection view 刷新闪动修改
[UIView performWithoutAnimation:^{
//刷新界面
[self.mycollectionview reloadData];
}];
# 修改alter view颜色字体
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self goCameraViewController];
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"手机上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self directGoPhotoViewController];
}];
UIAlertAction *action3 = [UIAlertAction actionWithTitle:[NSBundle hx_localizedStringForKey:@"取消"] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[action1 setValue:UIColorFromRGB(0xF44B50) forKey:@"_titleTextColor"];
[action2 setValue:UIColorFromRGB(0xF44B50) forKey:@"_titleTextColor"];
[action3 setValue:UIColorFromRGB(0x333333) forKey:@"_titleTextColor"];
[alertController addAction:action1];
[alertController addAction:action2];
[alertController addAction:action3];
[self.viewController presentViewController:alertController animated:YES completion:nil];
# 绘图的生命周期
-(void)viewDidLoad {
[super viewDidLoad];
_testView = [[TestView alloc] init];
NSLog(@"_testView 初始化完毕");
_testView.frame = CGRectMake(0, 0, 20, 20);
NSLog(@"_testView frame 初始化完毕");
[self.view addSubview:_testView];
NSLog(@"_testView 加载到父类完毕");
NSLog(@"viewDidLoad");
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear");
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"viewDidAppear");
}
2017-08-09 17:27:41.719 test2[89697:3696127] _testView 初始化完毕
2017-08-09 17:27:41.719 test2[89697:3696127] _testView frame 初始化完毕
2017-08-09 17:27:41.720 test2[89697:3696127] _testView 加载到父类完毕
2017-08-09 17:27:41.720 test2[89697:3696127] viewDidLoad
2017-08-09 17:27:41.720 test2[89697:3696127] viewWillAppear
2017-08-09 17:27:41.724 test2[89697:3696127] layoutSubviews
2017-08-09 17:27:41.724 test2[89697:3696127] drawRect
2017-08-09 17:27:41.726 test2[89697:3696127] viewDidAppear
# iPhoneX 底部偏移
//去掉tabbar的透明度
[[UITabBar appearance] setTranslucent:NO];
# 设置textview显示框内容不可编辑不可选择。
textView.editable=NO;//设置可编辑属性
textView.selectable=NO;//设置可选择属性
# 防止输入时在中文后输入英文过长直接中文和英文换行
-(void)textViewDidChange:(UITextView *)textView {
//防止输入时在中文后输入英文过长直接中文和英文换行
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:14],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}
///防止拼音输入时,文本直接获取拼音
UITextRange *selectedRange = [textView markedTextRange];
NSString * newText = [textView textInRange:selectedRange]; //获取高亮部分
if(newText.length>0)
{
return;
}
# view 返回VC
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UIViewController * vc =[self viewController];
[vc.navigationController popToRootViewControllerAnimated:NO];
});
-(UIViewController *)viewController
{
//获取当前view的superView对应的控制器
UIResponder *next = [self nextResponder];
do {
if ([next isKindOfClass:[UIViewController class]]) {
return (UIViewController *)next;
}
next = [next nextResponder];
} while (next != nil);
return nil;
}
# 将 < 等类似的字符转化为HTML中的“<”等
-(NSString *)htmlEntityDecode:(NSString *)string
{
string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""];
string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];
string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"&lt;" goes to @"<" not @"<"
return string;
}
# 获取点击的indexpath
[cell.btnFreeBankCard addTarget:self action:@selector(unbundleBankCard:event:) forControlEvents:UIControlEventTouchUpInside];
/**
标记标签
@param sender 发送者
*/
-(void)unbundleBankCard:(UIButton *)sender event:(UIEvent *)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath =[self.tableView indexPathForRowAtPoint:currentTouchPosition];
........
处理 按钮点击事件
}
字典转NSData去掉空格换行
-(NSString *)convertToJsonData:(NSDictionary *)dict{
NSError *error; //NSJSONWritingSortedKeys NSJSONWritingPrettyPrinted 设置为nil可以去掉空格和换行
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:nil error:&error];
NSString *jsonString;
if (!jsonData) {
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; }
return jsonString;
}
iOS AES 加密
-(NSString*)AESstringPass:(NSDictionary *)dict{
NSString* jasonSting =[self convertToJsonData:dict];
//AES 加密
NSString* aeStr =[self AES128Encrypt:jasonStingkey:@"88888888888"];
//url字符串中具有特殊功能的特殊字符的字符串,或者中文字符,作为参数传递时,需要用encode处理一下对有特殊符号的URL做处理(将特殊字符进行转码)
aeStr = [self URLencodeString:aeStr];
returnaeStr;
}
加密
//AES加密 #import <CommonCrypto/CommonCrypto.h>#import <CommonCrypto/CommonDigest.h>
-(NSString*)AES128Encrypt:(NSString*)plainTextkey:(NSString*)key{
char keyPtr[kCCKeySizeAES128+1];
memset(keyPtr,0,sizeof(keyPtr));
[keygetCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUIntegerdataLength = [datalength];
size_tbufferSize = dataLength +kCCBlockSizeAES128;
void*buffer =malloc(bufferSize);
size_tnumBytesEncrypted =0;
CCCryptorStatuscryptStatus =CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
NULL,
[databytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if(cryptStatus ==kCCSuccess) {
NSData*resultData = [NSDatadataWithBytesNoCopy:bufferlength:numBytesEncrypted];
NSString*stringBase64 = [resultDatabase64EncodedStringWithOptions:0];
//base64格式的字符串
returnstringBase64;
}
free(buffer);
return nil;
}
url字符串encode处理一下
-(NSString*)URLencodeString:(NSString*)unencodedString{
// CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
// CharactersToLeaveUnescaped = @"[].";
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
return encodedString;
}
AFNetworking Post 加密字符串给服务器
-(void)PostString:(NSString*)URLStringPostString:(id)dict succeed:(void(^)(id))succeed failure:(void(^)(NSError*))failure{
//创建网络请求管理对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval = 30;
manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString*_Nonnull(NSURLRequest*_Nonnull request,id _Nonnull parameters,NSError*_Nullable__autoreleasing*_Nullable error) {
//在这里面对parameters进行处理
return dict;
}];
[manager POST:URLString parameters:dict progress:nil success:^(NSURLSessionDataTask*_Nonnull task,id _Nullable responseObject) { NSDictionary * jasonDic =[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
succeed(jasonDic);
if(![jasonDic[@"status"]isEqualToString:@"SUCCESS"]) {
NSString* strinfo =[NSString stringWithFormat:@"%@",jasonDic[@"data"][@"info"]];
}
}failure:^(NSURLSessionDataTask*_Nullable task,NSError*_Nonnull error) {
failure(error);
}];
}
UINavigationController下移不能铺满全屏
在iOS13之前UINavigationController默认属性是UIModalPresentationFullScreen;
在iOS13默认属性是UIModalPresentationAutomatic;
所以我们要手动设置 NavigationController.modalPresentationStyle = UIModalPresentationFullScreen;
nil passed to a Callee that requires a non-null 1st parameter
意思是形参不能传nil。
Object leaked: object allocated and stored into 'CoreFoundation' is not referenced later in this execution path and has a retain count of +1
CoreFoundation 使用了Create 就要使用 CFRelease( );
Returning 'self' while it is not set to the result of '[(super
self= [super initWithStyle:stylereuseIdentifier:reuseIdentifier];
if (self) {
}
return self;
Value stored to 'MainViewColor' during its initialization is never read
定义的数据没被使用直接注释就可以了
Xcode 11.4.1 Building for iOS Simulator, but the linked library '******.a' was built for iOS.
解决办法
Xcode->File->Workspace Settings->Build System->Legacy Build System