1.按钮多选循环字典通过tag判断
点击下一步时字典记得初始化
for (NSInteger i = 10; i < _arraycount1.count +10; i++) {
UIButton *tempButton = (UIButton *)[self.view viewWithTag:100 + i - 10];
if (btn.tag == i) {
for (NSString *key in self.duoxuandic.allKeys) {
if ([key integerValue ] == i) {
if ([self.duoxuandic[key]integerValue] == 0) {
[tempButton setImage:[UIImage imageNamed:@"选中-30.png"] forState:UIControlStateNormal];
[_arr addObject:_arraycount2[i-10]];
self.duoxuandic[key] = [NSNumber numberWithBool:YES];
}else{
[tempButton setImage:[UIImage imageNamed:@"未选中-30.png"] forState:UIControlStateNormal];
self.duoxuandic[key] = [NSNumber numberWithBool:NO];
[_arr removeLastObject];
}
}
}
}
2.把数组里的元素以字符串形式展现出来并且用逗号隔开
NSString *string = [array componentsJoinedByString:@","]
取出字符串下标前后的字符串
[string substringToIndex:7];
substringFromIndex
//截取下标6后一位的字符串
[sr substringWithRange:NSMakeRange(6, 1)]
3.self.automaticallyAdjustsScrollViewInsets = NO;防止tableView的cell上移下移
4.每次进入页面刷新数据流程
[_arrayCount removeAllObjects];
[self request];
5.tableViewcell位置窜动
当 tableView 的内容比较多时底部的内容反而显示不下。这就很奇怪了,按照前面的结论,这时候 tableView是从导航栏底部开始布局的,contentInset 也是(0,0,0,0),怎么底部的内容会被遮挡一部分呢?原因在于self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
初始化时 rootView 的 frame 还是(0,0,screenWidth,screenHeight),只需要在viewWillLayoutSubviews
中重新修改一下 tableview 的 frame 即可,
- (void)viewWillLayoutSubviews{ [super viewWillLayoutSubviews]; _tableView.frame = self.view.bounds;
}
6.提取App的UI素材
打开iTunes,在App Store下载觉得UI不错的App,下载完成以后可以在我的应用中看到App。将App直接拖拽到桌面,得到App的ipa文件,下载第三方工具 iOSImagesExtractor
,下载地址https://github.com/devcxm/iOS-Images-Extractor
7.block的实质定义
你需要区分是说block对象,还是block里面的代码段。
block对象就是一个结构体,里面有isa指针指向自己的类(global malloc stack),有desc结构体描述block的信息,__forwarding指向自己或堆上自己的地址,如果block对象截获变量,这些变量也会出现在block结构体中。最重要的block结构体有一个函数指针,指向block代码块。block结构体的构造函数的参数,包括函数指针,描述block的结构体,自动截获的变量(全局变量不用截获),引用到的__block变量。(__block对象也会转变成结构体)
block代码块在编译的时候会生成一个函数,函数第一个参数是前面说到的block对象结构体指针。执行block,相当于执行block里面__forwarding里面的函数指针。
我被面试的话,我会接下来和面试官讨论一下block中内存管理相关知识。
用self调用带有block的方法会引起循环引用, 并不是所有通过self调用带有block的方法会引起循环引用,需要看方法内部有没有持有self。
使用weakSelf 结合strongSelf
的情况下,能够避免循环引用,也不会造成提前释放导致block内部代码无效。
/*
防止block循环引用: __weak __typeof(self) weakSelf = self;
__strong typeof(weakSelf) strongSelf = weakSelf;
*/
8.点击UITextView时键盘弹出挡住控件时的方法
//注册键盘出现与隐藏时候的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboadWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
-
(void)keyboardWillShow:(NSNotification *)aNotification {
/* 获取键盘的高度 */
NSDictionary *userInfo = aNotification.userInfo;
NSValue aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = aValue.CGRectValue;
/ 输入框上移 */
CGRect frame = yijianView.frame;
CGFloat height = kHeight - frame.origin.y - frame.size.height;
if (height < keyboardRect.size.height) {[UIView animateWithDuration:0.5 animations:^ { CGRect frame = self.view.frame; frame.origin.y = -(keyboardRect.size.height - height ); self.view.frame = frame; }];
}
} -
(void)keyboardWillHide:(NSNotification *)aNotification {
/* 输入框下移 */
[UIView animateWithDuration:0.5 animations:^ {
CGRect frame = self.view.frame;
frame.origin.y = kStatusBarHeight;
self.view.frame = frame;
}];
}
9.关于AutoLayoutd的讲解http://www.tuicool.com/articles/AF3UFn2
//禁止自动转换AutoresizingMask
btn2.translatesAutoresizingMaskIntoConstraints = NO;
//居中
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:btn2
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.45
constant:0]];
//距离底部20单位
//注意NSLayoutConstraint创建的constant是加在toItem参数的,所以需要-20。
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:btn2
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:0.65
constant:0]];
//定义高度是父View的三分之一
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:btn2 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.22 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:btn2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0.22 constant:0]];
10.给按钮添加动画
CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
rotationAnimation.duration = 0.5;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 1;
[btn.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
11.滑动tableView cell重叠问题
重用机制调用的就是dequeueReusableCellWithIdentifier这个方法,方法的意思就是“出列可重用的cell”,因而只要将它换为cellForRowAtIndexPath(只从要更新的cell的那一行取出cell),就可以不使用重用机制,因而问题就可以得到解决,但会浪费一些空间
http://blog.csdn.net/mhw19901119/article/details/9083293
12.cell以及label的自适应
cell.textLabel.textAlignment=0;
cell.textLabel.numberOfLines=0;
[cell.textLabel sizeToFit];
- 获取网页滑动高度,一般在网页加载完给frame赋值webViewDidFinishLoad
self.webViewHeight = [[self.contentWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
14.加载UIWebView或者WKWebView时报错加下面的到info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
15.防止程序杀死的方法APPdelegate里添加
- (void)applicationDidEnterBackground:(UIApplication *)application {
[NSRunLoop currentRunLoop];
}
16.跳转页面隐藏底部tabbar在跳转方法添加self.hidesBottomBarWhenPushed = YES;
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
self.navigationController.navigationBar.translucent = YES;
}
17.分区呈现
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *tempArray = [self.arraycount[section]objectForKey:@"list"];
return tempArray.count;
}
18.在tableViewcell上监听cell上按钮的indexpath(哪一行)进行一些处理
// cell上'edit按钮'的点击事件-
(IBAction)editClick:(id)sender {
// create toVC
AddressEditTableController toVC = [[AddressEditTableController alloc] initWithStyle:UITableViewStyleGrouped];
// 获取'edit按钮'所在的cell
(1)第一种
UITableViewCell myCell = (UITableViewCell *)[btn superview];
NSIndexPath *index = [self.tableview indexPathForCell:myCell];
(2)第二种
UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
// 获取cell的indexPath
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
// 打印 --- test
NSLog(@"点击的是第%zd行",indexPath.row + 1);// 跳转
[self.navigationController pushViewController:toVC animated:YES];
}
19.点击cell上的某个控件删除这行cell
1). NSMutableArray *arr = self.arraycount[index.section];
[arr removeObjectAtIndex:index.row];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:(UITableViewRowAnimationFade)];
});
2). // 删除数据源
[strongSelf.addressArray removeObjectAtIndex:indexPath.row];
// 主线程更新UI
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.addressListTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationMiddle)];
20.//利用通知删除第一响应方法
- (void)setUpForDismissKeyboard {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
UITapGestureRecognizer *singleTapGR =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
[nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){
[self.view addGestureRecognizer:singleTapGR];
}];
[nc addObserverForName:UIKeyboardWillHideNotification object:nil
queue:mainQuene usingBlock:^(NSNotification *note){
[self.view removeGestureRecognizer:singleTapGR];
}];
} - (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
[self.view endEditing:YES];
}
21.给父view设置透明度不让子view受影响
view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
22.获取当前cell的index id
IFYDdthreeTableViewCell *cell = (IFYDdthreeTableViewCell *)[[btn superview]superview];
// 获取cell的indexPath
NSIndexPath *index = [self.tableView indexPathForCell:cell];
NSString *st = [self.arrayID[index.section] objectForKey:@"id"] ;
23.根据返回值获取文字宽度 不规则排序
//计算文字大小
CGSize titleSize = [_titleArr[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, titBtnH) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:titBtn.titleLabel.font} context:nil].size;
CGFloat titBtnW = titleSize.width + 2 * padding;
//判断按钮是否超过屏幕的宽
if ((titBtnX + titBtnW) > kScreenW) {
titBtnX = 0;
titBtnY += titBtnH + padding;
}
//设置按钮的位置
titBtn.frame = CGRectMake(titBtnX, titBtnY, titBtnW, titBtnH);
titBtnX += titBtnW + padding;
24.自动行高(需要配合autolayout自动布局)
self.tableView.estimatedRowHeight = 200; //预估行高self.tableView.rowHeight = UITableViewAutomaticDimension;
tableViewCell左滑功能
//tableView向左滑的功能
-(void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath{ self.tableView.editing = !self.tableView.editing; ChangeInfosController changeInfo = [[ChangeInfosController alloc]init]; [self.navigationController pushViewController:changeInfo animated:YES];}//修改左滑的文字-(NSString)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ return @"编辑";}
取消重用
NSString*CellIdentifier = [NSStringstringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];//以indexPath来唯一确定cellFillOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell if (cell == nil) { cell = [[FillOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
25.UINavigationBar偏移量
我们知道默认translucent = YES。就是Bar 是有透明度的。
在有透明度的情况下,系统默认automaticallyAdjustsScrollViewInsets属性是YES就是对于scrollerview的子类会默认content偏移64个单位。这样做的目的,既然Bar都是透明的了,系统就觉得你的scrollerView一定在会在(0,0)点,content偏移一个64个单位。在你滑动的时候,隐藏在Bar下面的Content会有一个模糊显示的效果。QAQ
如果你不想要这个偏移量
1 设置translucent = NO,既然Bar不透明。自然不需要偏移量喽
2 关闭这个偏移量,automaticallyAdjustsScrollViewInsets = NO
提一下像tableView,在storyboard 设置上下左右的约束。结果cell上面多了一块空白。就是这个问题。
26.// 解决TabBar遮挡
self.edgesForExtendedLayout = UIRectEdgeAll;
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, CGRectGetHeight(self.tabBarController.tabBar.frame), 0.0f);
27.uitextview设置占位符
遵循代理,label.enabled = NO,实现方法
- (void)textViewDidChange:(UITextView *)textView {
if (textView.text.length == 0) {
}
}
28.pop到指定的页面
IFYEShopViewController *homeVC = [[IFYEShopViewController alloc] init];
UIViewController *target = nil;
for (UIViewController * controller in self.navigationController.viewControllers) { //遍历
if ([controller isKindOfClass:[homeVC class]]) { //这里判断是否为你想要跳转的页面
target = controller;
}
}
if (target) {
[self.navigationController popToViewController:target animated:YES]; //跳转
}
29.往数组里插入数组
[_arrayquanxuan insertObjects:_waijiaArr atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, _waijiaArr.count)]];
- 字体变大变颜色
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%f",[yuyuejin floatValue] ]attributes:nil];
[attributedString setAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:0.97 green:0.38 blue:0.13 alpha:1.0]} range:NSMakeRange(6, 2)];
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:40] range:NSMakeRange(1, attributedString.length)];
jiage.text = [NSString stringWithFormat:@"约%@元", attributedString];
31.在请求数据时参数用下面的方法报错时先检查看看参数是否为nil,如果为nil则停止,解决办法为把为nil的参数在请求数据之前赋值
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"" :@"" , nil];
32.webview给后台传值传参数时不能传汉字如果有汉字 不会走代理方法
解决办法把汉字转utf8码
http://jingjizhuli.tuowei.com/jingjizhuli/CaiZhengShouRuWanChengQuXianTu.aspx?DanWei=全部&Value=-1&Year=2017
33.UIimageView设置圆角不好使将多余的部分切掉
//将多余的部分切掉
// _image.layer.masksToBounds = YES;
34.连续发出几个网络请求,等这几个请求完成才执行
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < 100; i++) {
dispatch_group_enter(group);
[[NetworkTool shareTool] post:url para:para block:^(id responseObject, NSError *error) {
dispatch_group_leave(group);
}
];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//请求完毕后的处理
});
- 请求数据时发现报错但是数据还保存上了 只是某一字段没保存上那就肯定是后台的毛病啦
直接报错-404 -500之类的是服务器出错少字段
在报错的位置打印一下就知道了
NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"服务器的错误原因:%@",str);
36.//json格式字符串转字典:
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
37.禁止粘贴标点及符号
define NUM @"0123456789"
define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
-
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == mobilePhoneTextField) {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];}
return textField;
}