目录
- maskView动画原理 :遮罩
- button倒计时闪烁解决
- 改变从xib拖出来约束,没有动画效果解决办法:添加 layoutIfNeeded
- 去除导航栏底部1px横线
- UIWebView直接打开PDF文件
- 改变StatusBar颜色
- UICollectionView 和 UITableView 顶部留白处理
- TableView底下多余的分割线去除
- webView真正加载完成
- UIButton 只有title的时候,把 title 靠左对齐
- Restoration ID 和 UITableViewCell 的identifier的区别
- UIButton 的 SEL 换成block
- UIImage指定范围内拉伸 - 聊天气泡背景图
- NSAttributeString设置文本位置居中、靠左
- 打开系统相机、使用searchBarController等 标题显示英文解决
- label 设置文字渐变色 [设置渐变色几种方式]
- 设置导航栏上返回图标和title为空
- Could not load NIB in bundle 错误。 nib文件存在,找不到,原因是没有选中 'Target Membership'
- Mac OS 系统更新到了 high Sierra ,pod 不能用了 报错
- 文本转语音播放
- present出来一个半透明的view controller
- NSAspects 使用
- UITextField 明文密文切换光标位置不准
- UITextField 右对齐在末尾输入空格不显示
- 禁用第三方键盘
- OC计算字符串中字符个数(汉字2个字符,英文字母、数字、空格1个字符)
- iOS 启动图问题
- 简书生成图片分享iOS实现
- bundle name 和 bundle display name
- Localizations中Resources中显示0 files Localized
- 获取当前系统语言
- 打包上传APP到iTunes connect时候出错。
- UIPickerView UIDatePicker 分割线去除
- 各一个有圆角的view添加阴影效果
- 设置按钮不可点击状态时的背景色,颜色有误差。原因是系统自动加了层蒙版。
- 自定义返回按钮导致系统的右滑返回手势失效
- 隐藏导航栏
- pop到上上一级vc
- uitextfield输入内容过长时候,字符不自动左移问题
- 导航栏上添加视图frame问题
- 同时重写setter getter ,实例变量报错问题
- 选择模拟器/真机,显示no scheme
- Xcode增加编译环境 debug release 新增preProduct
- UITextField光标换成图片
- 封装pod库时带上资源bundle
- UISider滑动和pan手势滑动冲突
- 键盘弹起自动上滑tableview
- Cancle换成汉字『取消』
- 日期格式化 https://www.cnblogs.com/Cristen/p/3599922.html
- 已经纳入版本管理的文件,加入.gitignore不生效的问题
- git添加子模块submodule
- git移除子模块
- 去除main.storyboard
- cell选中时,子视图背景颜色受影响
- didselected方法不管用
随手记
maskView动画原理 :遮罩
-
button倒计时闪烁解决
把按钮样式设为custom而非system
-
把下面代码中注释掉的两行放开
-(void)ticktack { __block int timeout = 59; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0); dispatch_source_set_event_handler(_timer, ^{ dispatch_async(dispatch_get_main_queue(), ^{ if (timeout <= 0) {//倒计时结束,关闭 dispatch_source_cancel(_timer); // self.sendCodeBtn.titleLabel.text = @"获取验证码"; [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal]; self.sendCodeBtn.userInteractionEnabled = YES; self.sendCodeBtn.enabled = YES; } else { // self.sendCodeBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒后重新发送",timeout]; [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新发送",timeout] forState:UIControlStateNormal]; self.sendCodeBtn.userInteractionEnabled = NO; self.sendCodeBtn.enabled = NO; timeout--; } }); }); dispatch_resume(_timer); }
-
改变从xib拖出来约束,没有动画效果解决办法:添加 layoutIfNeeded
[UIView animateWithDuration:0.5 animations:^{ self.passwdLoginContainLeadingContain.constant = -ScreenWidth; [self.view layoutIfNeeded]; } completion:^(BOOL finished) { }];
-
去除导航栏底部1px横线
UINavigationBar *navBar = self.navigationController.navigationBar; [navBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; [navBar setShadowImage:[UIImage new]];
-
UIWebView直接打开PDF文件
NSURLRequest *req = [NSURLRequest alloc] initWithUrl:[NSURL urlWithfilePath:filePath]]; webView.scalesPageToFit = YES; webView.loadRequest
-
改变StatusBar颜色
UINavigationBar *navBar = self.navigationController.navigationBar; _statusView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, ScreenWidth, 20)]; _statusView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1]; [navBar addSubview:_statusView];
-
UICollectionView 和 UITableView 顶部留白处理
self.automaticallyAdjustsScrollViewInsets = NO
-
TableView底下多余的分割线去除
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
-
webView真正加载完成
webViewDidFinishLoad: 方法在页面重定向的时候会被多次加载,用webView.isLoading判断是否还在加载
-
UIButton 只有title的时候,把 title 靠左对齐
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left // btn.titleLabel?.textAlignment = NSTextAlignment.left 这句不管用
Restoration ID 和 UITableViewCell 的identifier的区别
- Restoration ID Preserving and Restoring State
用于存储和恢复应用状态。一个应用进入后台,再进入前台显示的还是之前的页面,优化用户体验 - Identifer 用于从xib或者故事版里创建一个实例
- UIButton 的 SEL 换成block
@class QSBlockButton;
#pragma mark class QSBlockButton
typedef void(^ActionBlock)(QSBlockButton *);
@interface QSBlockButton : UIButton
@property (copy, nonatomic) ActionBlock block;
@end
@implementation QSBlockButton
- (instancetype)init {
self = [super init];
if (self) {
[self addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)touchAction:(id)sender{
_block(self);
}
-
UIImage指定范围内拉伸 - 聊天气泡背景图
UIImage *imgBack = [bkImg stretchableImageWithLeftCapWidth:0 topCapHeight:2];
NSAttributeString设置文本位置居中、靠左
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc]init];
paragraph.alignment = NSTextAlignmentJustified;
NSDictionary *dic = @{NSParagraphStyleAttributeName : paragraph]};
打开系统相机、使用searchBarController等 标题显示英文解决:在
info.plist
中添加Localized resources can be mixed
设为YES
-
label 设置文字渐变色 设置渐变色几种方式
方式一 : NSArray *gradientColors = @[(id)ColorFromRGB(0xff7f43).CGColor, (id)ColorFromRGB(0xff3609).CGColor]; _titleLabel = [[UILabel alloc] init]; self.titleLabel.text = title; self.titleLabel.font = [UIFont systemFontOfSize:12]; [self.titleLabel sizeToFit]; if (self.titleLabel.frame.size.width > self.rightView.frame.size.width) { self.titleLabel.frame = CGRectMake(0, 0, self.rightView.frame.size.width, self.rightView.frame.size.height); } else { self.titleLabel.frame = CGRectMake(self.rightView.frame.size.width - _titleLabel.frame.size.width, (self.rightView.frame.size.height-_titleLabel.frame.size.height)/2, _titleLabel.frame.size.width, _titleLabel.frame.size.height); } [self.rightView addSubview:self.titleLabel]; // 创建渐变层 CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = self.titleLabel.frame; gradientLayer.colors = gradientColors; gradientLayer.startPoint = CGPointMake(0, 1); gradientLayer.endPoint = CGPointMake(1, 1); NSArray *layers = self.rightView.layer.sublayers; NSMutableArray *murr = [NSMutableArray arrayWithArray:layers]; for (CALayer *l in murr) { if ([l isKindOfClass:[CAGradientLayer class]]) { [l removeFromSuperlayer]; } } [self.rightView.layer addSublayer:gradientLayer]; gradientLayer.mask = self.titleLabel.layer; self.titleLabel.frame = gradientLayer.bounds;
-
设置导航栏上返回图标和title为空
self.navigationController?.navigationBar.backIndicatorImage = #imageLiteral(resourceName: "back").withRenderingMode(.alwaysOriginal) self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
-
Could not load NIB in bundle 错误。 nib文件存在,找不到,原因是没有选中 'Target Membership'
-
Mac OS 系统更新到了 high Sierra ,pod 不能用了 报错:
-bash: /usr/local/bin/pod: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby: bad interpreter: No such file or directory
解决:重新安装cocoapods ‘sudo gem install cocoapods’
-
文本转语音播放
let utterance = AVSpeechUtterance.init(string: "Hello,我觉得吧...") let synthesizer = AVSpeechSynthesizer.init() synthesizer.speak(utterance)
NSTimer后台运行
- (void)viewDidLoad {
[super viewDidLoad];
_count = 10;
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
_timer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ticktock:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:(NSRunLoopCommonModes)];
}
- (void)ticktock:(NSTimer *)sender {
if (_count > 0) {
_count--;
_label.text = [NSString stringWithFormat:@"%ld",_count];
NSLog(@"%@",_label.text);
}
else {
[_timer invalidate];
}
}
-
present出来一个半透明的view controller
DSBirthdayViewController *birthdayVC = [[DSBirthdayViewController alloc] init]; birthdayVC.modalPresentationStyle = UIModalPresentationOverCurrentContext; [self presentViewController:birthdayVC animated:YES completion:^{ }];
-
NSAspects 使用
[NSAspects hookMethodForObject:people selector:@selector(drink) withOptions:(AspectPositionInstead | AspectOptionAutomaticRemoval ) usingBlock:^(void){ NSLog(@"eat"); } error:nil];
UITextField 明文密文切换光标位置不准
两种解决方式: 1. 注释中语句 2. if 里语句
-
UITextField 右对齐在末尾输入空格不显示
//1. 自定义TextField // .h @interface MTTextField : UITextField @end //.m @implementation MTTextField - (instancetype)init { self = [super init]; if (self) { [self addTarget:self action:@selector(replaceNormalSpaceUsingNonbreakingSpace) forControlEvents:UIControlEventEditingChanged]; } return self; } - (void)replaceNormalSpaceUsingNonbreakingSpace { UITextRange *textRange = self.selectedTextRange; self.text = [self.text stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"]; [self setSelectedTextRange:textRange]; } //2. 使用的时候 [[MTObserve(cell.textField, text) skip:1] subscribeNext:^(NSString *x) { @strongify(self) NSString *text = [x stringByReplacingOccurrencesOfString:@"\u00a0" withString:@" "]; self.modifyInfoViewModel.nickname = [text trim]; }];
-
禁用第三方键盘
//全局禁第三方键盘 - (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier { return NO; } //某个uitextfield禁第三方键盘 [原文](https://www.pixotech.com/ios8_third_party_custom_keyboard_compatibility/) #pragma mark - 禁用三方键盘 - (BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier { if ([extensionPointIdentifier isEqualToString: UIApplicationKeyboardExtensionPointIdentifier]) { id responder = [self findFirstResponder]; if ([responder isKindOfClass:[UITextField class]]) { return NO; } } return YES; } id mt_firstResponder; -(id)findFirstResponder { mt_firstResponder = nil; [[UIApplication sharedApplication] sendAction:@selector(foundFirstResponder:) to:nil from:nil forEvent:nil]; return mt_firstResponder; } -(void)foundFirstResponder:(id)sender { mt_firstResponder = self; }
-
OC计算字符串中字符个数(汉字2个字符,英文字母、数字、空格1个字符)
- (NSUInteger)textLength: (NSString *) text { NSUInteger asciiLength = 0; for (NSUInteger i = 0; i < text.length; i++) { unichar uc = [text characterAtIndex: I]; asciiLength += isascii(uc) ? 1 : 2; } NSUInteger unicodeLength = asciiLength; return unicodeLength; }
-
iOS 启动图问题
确认各项配置都正确,但是启动图就是不出来。试试删除app,然后重启手机🤦♂️。
Gernal 配置 App Icon and Launch Images 一项时候。使用 Launch Image Source. 而不是 Launch Screen File 时候。要把 4寸屏幕的启动图也加上,不然会导致在 4寸屏幕手机上运行时候,上下有黑色。
- 简书生成图片分享iOS实现
// 内容都放到textView里
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextView *textView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)action:(id)sender {
UIImage *image = [self imageWithScreenContentsInView:_textView];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}
//在指定的视图内进行截屏操作,返回截屏后的图片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view
{
//根据屏幕大小,获取上下文
UIGraphicsBeginImageContext(_textView.contentSize);
[_textView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"\n=======%@=========\n",NSStringFromClass([obj class]));
if ([NSStringFromClass([obj class]) isEqualToString:@"_UITextContainerView"]) {
[obj.layer renderInContext:UIGraphicsGetCurrentContext()];
}
}];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{
if(!error) {
NSLog(@"合影已保存到相册");
}else{
NSLog(@"合影保存失败");
}
}
@end
- bundle name 和 bundle display name
bundle name
is folder name, where your app (including executable file and all resources) will be stored (Cool Program.app)。建议不要修改bundle name (http://blog.csdn.net/kkk0526/article/details/9198355)bundle display name
is what will be shown on iPhone screen,即当你安装该app到iPhone上显示的name。 (http://blog.csdn.net/kkk0526/article/details/9198355)
- Localizations中Resources中显示0 files Localized
原因:这是因为把main.storyboard LaunchImage.storyboard 都删除了。这时候想要添加国际化语言因为是0所以添加不了。
解决:暂时添加个LaunchImage.storyboard,等国际化做好后,就可以删掉了。
- 获取当前系统语言
- (BOOL)isRightLanguages {
NSString *current = [[NSLocale preferredLanguages] objectAtIndex:0];//当前语言 h-Hans-CN 简体中文, zh-Hant-MO繁体中文, en-CN 英文
NSArray *supports = [[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"];
BOOL is = NO;
for (NSString *sub in supports) {
if ([sub isEqualToString:current]) {
is = YES;
}
}
return is;
}
-
打包上传APP到iTunes connect时候出错。
ERROR ITMS-90475: "Invalid Bundle. Your app supports Multitasking on iPad, so you must include the UILaunchStoryboardName key in your bundle, 'com.sun.allen.app’. Learn more (https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html#//apple_ref/doc/uid/TP40009252-SW40)."
解决:
-
UIPickerView UIDatePicker 分割线去除
// date picker 分割线去除 self.datePicker.subviews.firstObject.subviews - (void)clearSeparatorView { [self.datePicker.subviews.firstObject.subviews enumerateObjectsUsingBlock:^( UIView *obj, NSUInteger idx, BOOL * stop) { if (obj.frame.size.height < 1) { obj.hidden = YES; } }]; } //UIPickerView 分割线去除 - (void)clearSeparatorView { [self.genderPickerView.subviews enumerateObjectsUsingBlock:^( UIView *obj, NSUInteger idx, BOOL * stop) { if (obj.frame.size.height < 1) { obj.hidden = YES; } }]; }
各一个有圆角的view添加阴影效果
MTDealSaleCardView *card = [[MTDealSaleCardView alloc] init];
card.layer.cornerRadius = 4.f;
// card view 的 masksToBounds = YES; 会把阴影效果也切掉。所以要给它增加一个父视图,对父视图做阴影效果
card.layer.masksToBounds = YES;
card.layer.borderColor = [UIColor colorWithHexString:@"#e4e4e4"].CGColor;
card.layer.borderWidth = 0.5;
/**
创建一个cardContainerView盛放card , 对 cardContainerView 做阴影效果
@param card card
@return card的父视图
*/
- (UIView *)createCardShadowEffect:(MTDealSaleCardView *)card {
UIView *cardContainerView = [[UIView alloc] init];
[cardContainerView addSubview:card];
[card mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.right.bottom.equalTo(cardContainerView);
}];
//阴影
cardContainerView.layer.shadowColor = [UIColor colorWithHexString:@"0f000000"].CGColor;
cardContainerView.layer.shadowColor = [UIColor yellowColor].CGColor; //todo
cardContainerView.layer.shadowOffset = CGSizeMake(0, 0);
cardContainerView.layer.shadowRadius = 4.f;
cardContainerView.layer.shadowOpacity = 1;
UIBezierPath *path = [UIBezierPath bezierPath];
CGFloat addWH = 4.f;
CGFloat selfWidth = MTRealTimePriceTableViewCell_CardWidth;
CGFloat selfHeight = MTRealTimePriceTableViewCell_CardHeight;
CGPoint topLeft = CGPointMake(0, 0);
CGPoint topMiddle = CGPointMake(selfWidth/2, -addWH);
CGPoint topRight = CGPointMake(selfWidth, 0);
CGPoint leftMiddle = CGPointMake(-addWH, selfHeight/2);
CGPoint leftBottom = CGPointMake(0, selfHeight);
CGPoint rightMiddel = CGPointMake(selfWidth+addWH, selfHeight/2);
CGPoint rightBottom = CGPointMake(selfWidth, selfHeight);
CGPoint bottomMiddel = CGPointMake(selfWidth/2, selfHeight+addWH);
[path moveToPoint:topLeft];
[path addQuadCurveToPoint:topRight controlPoint:topMiddle];
[path addQuadCurveToPoint:rightBottom controlPoint:rightMiddel];
[path addQuadCurveToPoint:leftBottom controlPoint:bottomMiddel];
[path addQuadCurveToPoint:topLeft controlPoint:leftMiddle];
cardContainerView.layer.shadowPath = path.CGPath;
cardContainerView.backgroundColor = [UIColor whiteColor];
return cardContainerView;
}
- 设置按钮不可点击状态时的背景色,颜色有误差。原因是系统自动加了层蒙版。
解决:不使用state,而是通过修改button的是否可交互属性。
//此处不使用按钮绑定command,而是控制按钮的userInteractionEnabled。
//原因是使用绑定command时候,直接设置按钮UIControlStateDiabled的背景颜色,系统会自动加上一层蒙版 导致颜色值不对。
// self.rechargeButton.rac_command = self.viewModel.rechargeCommand;
[self.viewModel.rechargeCommand.enabled subscribeNext:^(NSNumber *x) {
@strongify(self)
if (x.boolValue) {
self.rechargeButton.userInteractionEnabled = YES;
[self.rechargeButton setBackgroundImage:[UIImage imageWithColor:MTThemeColor]
forState:(UIControlStateNormal)];
[self.rechargeButton setTitleAttributes:@{NSFontAttributeName: [UIFont mediumSystemFontOfSize:15], NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#333333"]}
forState:(UIControlStateNormal)];
} else {
self.rechargeButton.userInteractionEnabled = NO;
[self.rechargeButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"ececec"]]
forState:(UIControlStateNormal)];
[self.rechargeButton setTitleAttributes:@{NSFontAttributeName: [UIFont mediumSystemFontOfSize:15], NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#c5c5c5"]}
forState:(UIControlStateNormal)];
}
}];
[[self.rechargeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
@strongify(self)
[self.viewModel.rechargeCommand execute:nil];
}];
-
自定义返回按钮导致系统的右滑返回手势失效
// 添加上这一行就解决了 self.navigationController.interactivePopGestureRecognizer.delegate = (id)self; // - (void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; if (self.navigationController.viewControllers.count > 1) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; }else{ self.navigationController.interactivePopGestureRecognizer.enabled = NO; } }
-
pop到上上一级vc
for (NSInteger i = 0; i<self.navigationController.childViewControllers.count; i++) { UIViewController *child = [self.navigationController.childViewControllers objectOrNilAtIndex:i]; if ([child isKindOfClass:[MTApplyRedemptionViewController class]]) { NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.navigationController.childViewControllers]; [tempArr removeObject:child]; [self.navigationController setViewControllers:tempArr]; break; } }
uitextfield输入内容过长时候,字符不自动左移问题 iOS10以下
解决: 增加uitextfield高度
- 导航栏上添加视图frame问题
- (SSPageControl *)pageControl {
if (!_pageControl) {
_pageControl = [[SSPageControl alloc] initWithFrame:CGRectMake(0, 0, 106, 4)];//106是有9张图片的时候的最大宽度 .//必须一开始就把宽度写死,如果动态改变的话会导致iOS10上 pageControl跳动
_pageControl.userInteractionEnabled = NO;
_pageControl.controlNormalSize = 4.f;
_pageControl.controlCurrentSize = 10.f;
_pageControl.controlSpacing = 8.f;
_pageControl.otherBkImg = [UIImage imageWithColor:[UIColor colorWithHexString:@"ffffff50"]];
_pageControl.currentBkImg = [UIImage imageWithColor:[UIColor colorWithHexString:@"ffffff"]];
_pageControl.hidden = YES;
}
return _pageControl;
}
- (void)configurationPageControl {
self.pageControl.numberOfPages = self.viewModel.imageArray.count;
self.pageControl.currentPage = 0;
CGFloat width = [self.pageControl sizeThatFits:CGSizeZero].width;
CGFloat height = self.pageControl.controlNormalSize;
// self.pageControl.frame = CGRectMake(0.0, 0.0, width, height); //不能动态的改变frame
self.pageControl.hidden = (self.viewModel.imageArray.count == 1);
}
self.navigationItem.titleView = self.pageControl;
-
同时重写setter getter ,实例变量报错问题
选择模拟器/真机,显示no scheme
[解决 点击 NO Scheme,新增一个] (https://blog.csdn.net/QearlYu/article/details/53466699)
- Xcode增加编译环境 debug release 新增preProduct
https://blog.csdn.net/FreshManCode/article/details/80354936
- UITextField光标换成图片
- 封装pod库时带上资源bundle
获取bundle
+ (NSBundle *)ucar_resourceBundle {
NSBundle *bundle = [NSBundle bundleForClass:[TestProjClass class]];
NSURL *url = [bundle URLForResource:@"testProj" withExtension:@"bundle"];
bundle = [NSBundle bundleWithURL:url];
return bundle;
}
获取图片
+ (UIImage *)getImg {
NSLog(@"哈哈哈哈");
NSBundle *bundle = [NSBundle ucar_resourceBundle];
UIImage *image = [UIImage imageNamed:@"ucar_pause.png" inBundle:bundle compatibleWithTraitCollection:nil];
return image;
}
podspec文件中写好bundle路径,把pod库发布出去
s.resource_bundles = {
'testProj' => ['testProj/testProj/testProj/testProj.bundle'],
}
使用示例如下:
-
UISider滑动和pan手势滑动冲突
#pragma mark - UIGestureRecognizerDelegate -(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch { if ([gestureRecognizer isEqual:self.panGR] && [touch.view isEqual:self.progressSilder]) { return NO;// 防止pan手势影响UISlider的响应 } return YES; }
键盘弹起自动上滑tableview
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)aNotification {
NSDictionary* info = [aNotification userInfo];
// 注意不要用UIKeyboardFrameBeginUserInfoKey,第三方键盘可能会存在高度不准,相差40高度的问题
CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
// 修改滚动天和tableView的contentInset
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
// 跳转到当前点击的输入框所在的cell
[UIView animateWithDuration:0.2 animations:^{
[self.tableView scrollToRowAtIndexPath:self.beginEditIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}];
}
- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
self.tableView.contentInset = UIEdgeInsetsZero;
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}
- Cancle换成汉字『取消』
修改info.plist中 "Localization native development region" 成 "China"
已经纳入版本管理的文件,加入.gitignore不生效的问题
.gitignore只能忽略那些原来没有被track的文件,如果某些文件已经被纳入了版本管理中,则修改.gitignore是无效的。
只能clone到本地,删除后,再进行忽略。
- git添加子模块submodule
$ git submodule add https://github.com/xxx.git
Cloning into 'xxx'...
remote: Counting objects: 11, done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 11 (delta 0), reused 11 (delta 0)
Unpacking objects: 100% (11/11), done.
Checking connectivity... done.
- git移除子模块
-
cd .git
切换到.git目录,修改config,删掉submodule
-
cd modules
,删除子模块目录 -
cd 项目根目录
删除子模块目录
- 去除main.storyboard
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let win = UIWindow.init(frame: UIScreen.main.bounds)
win.rootViewController = BWRootTabBarController()
win.backgroundColor = UIColor.white
win.makeKeyAndVisible()
self.window = win
return true
}
- cell选中时,子视图背景颜色受影响
- (void)layoutSubviews {
[super layoutSubviews];
self.statusLabel.backgroundColor = [UIColor colorWithHexRGBAString:@"#FF5B45"];
}
- didselected方法不管用
- item/cell上有button或者手势响应了点击事件
Xcode配置
debug包没问题、release包出问题原因。解决方法: 打Release包的时候把 Optimization Level 改成 None, Debug 模式默认就是 None 所以才没问题。
’The file “XXX.app” couldn’t be opened because you don’t have permission to view it.‘ 解决办法: info文件中的字段 Executable file 改成$(PRODUCT_NAME)。
[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
解决:
其他
-
ARC环境中使用weak 的修饰符来修饰一个变量,防止其在block中被循环引用,而有些特殊情况下,我们在block中又使用_strong 来修饰这个在block外刚刚用_weak修饰的变量,这是因为在block中调用self会引起循环引用,而在block中需要对weakSelf进行__strong,保证代码在执行到block中,self不会被释放,当block执行完后,会自动释放该strongSelf
eg: AFNetworkReachabilityManager.m 文件中 __weak __typeof(self)weakSelf = self; AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { __strong __typeof(weakSelf)strongSelf = weakSelf; strongSelf.networkReachabilityStatus = status; if (strongSelf.networkReachabilityStatusBlock) { strongSelf.networkReachabilityStatusBlock(status); } };
block一般用copy修饰。block 使用 copy 是从 MRC 遗留下来的“传统”,在 MRC 中,方法内部的 block 是在栈区的,使用 copy 可以把它放到堆区.在 ARC 中写不写都行:对于 block 使用 copy 还是 strong 效果是一样的,但写上 copy 也无伤大雅,还能时刻提醒我们:编译器自动对 block 进行了 copy 操作。如果不写 copy ,该类的调用者有可能会忘记或者根本不知道“编译器会自动对 block 进行了 copy 操作”,他们有可能会在调用之前自行拷贝属性值。这种操作多余而低效。
PS1: 这段话引自@iOS程序犭袁 的OGitHub - ChenYilong/iOSInterviewQuestions:...《招聘一个靠谱的iOS》面试题参考答案/《招聘一个靠谱的iOS》面试题参考答案(上).md
PS2: 苹果官方建议。delegate一般用weak修饰,这是为了防止内存泄漏。比方说一个viewController持有一个tableview,tableview的代理是这个viewController。如果用strong修饰delegate,就会造成循环引用。
从xib或者storyboard上拖出来一个控件A,自动就是weak修饰。这是因为控件A放到xib上,已经被xib上的view强引用了。A的创建位置是在xib上,我们在声明属性的位置是要得到这个控件A的引用,用weak就可以了,不会增加引用计数。
OC写方法的时候没写返回值类型[doge],编译运行通过,默认是id
OC向nil发消息不回崩溃