Last active
October 23, 2019 07:27
-
-
Save iHTCboy/20106e680904728f8b4f213e983fe08b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################ | |
//获取当前屏幕显示的viewcontroller | |
- (UIViewController *)getCurrentVC | |
{ | |
UIViewController *result = nil; | |
UIWindow * window = [[UIApplication sharedApplication] keyWindow]; | |
if (window.windowLevel != UIWindowLevelNormal) | |
{ | |
NSArray *windows = [[UIApplication sharedApplication] windows]; | |
for(UIWindow * tmpWin in windows) | |
{ | |
if (tmpWin.windowLevel == UIWindowLevelNormal) | |
{ | |
window = tmpWin; | |
break; | |
} | |
} | |
} | |
UIView *frontView = [[window subviews] objectAtIndex:0]; | |
id nextResponder = [frontView nextResponder]; | |
if ([nextResponder isKindOfClass:[UIViewController class]]) | |
result = nextResponder; | |
else | |
result = window.rootViewController; | |
return result; | |
} | |
然后在想使用的地方,直接就可以调用这个函数,然后加上了,比如说现在声明的那个view里面写了这个,当想加上去的时候可以直接这样 | |
[[self getCurrentVC].view addSubview:self] | |
################################################################ | |
IOS 遍历未知对象的属性和方法 | |
/* 注意:要先导入ObjectC运行时头文件,以便调用runtime中的方法*/ | |
#import <objc/runtime.h> | |
@implementation NSObject (PropertyListing) | |
//1、/* 获取对象的所有属性,不包括属性值 */ | |
- (NSArray *)getAllProperties | |
{ | |
u_int count; | |
objc_property_t *properties =class_copyPropertyList([self class], &count); | |
NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count]; | |
for (int i = 0; i<count; i++) | |
{ | |
const char* propertyName =property_getName(properties[i]); | |
[propertiesArray addObject: [NSString stringWithUTF8String: propertyName]]; | |
} | |
free(properties); | |
return propertiesArray; | |
} | |
//2、/* 获取对象的所有属性 以及属性值 */ | |
- (NSDictionary *)properties_aps | |
{ | |
NSMutableDictionary *props = [NSMutableDictionary dictionary]; | |
unsigned int outCount, i; | |
objc_property_t *properties = class_copyPropertyList([self class], &outCount); | |
for (i = 0; i<outCount; i++) | |
{ | |
objc_property_t property = properties[i]; | |
const char* char_f =property_getName(property); | |
NSString *propertyName = [NSString stringWithUTF8String:char_f]; | |
id propertyValue = [self valueForKey:(NSString *)propertyName]; | |
if (propertyValue) [props setObject:propertyValue forKey:propertyName]; | |
} | |
free(properties); | |
return props; | |
} | |
//3、/* 获取对象的所有方法 */ | |
-(void)printMothList | |
{ | |
unsigned int mothCout_f =0; | |
Method* mothList_f = class_copyMethodList([self class],&mothCout_f); | |
for(int i=0;i<mothCout_f;i++) | |
{ | |
Method temp_f = mothList_f[i]; | |
IMP imp_f = method_getImplementation(temp_f); | |
SEL name_f = method_getName(temp_f); | |
const char* name_s =sel_getName(method_getName(temp_f)); | |
int arguments = method_getNumberOfArguments(temp_f); | |
const char* encoding =method_getTypeEncoding(temp_f); | |
NSLog(@"方法名:%@,参数个数:%d,编码方式:%@",[NSString stringWithUTF8String:name_s], | |
arguments,[NSString stringWithUTF8String:encoding]); | |
} | |
free(mothList_f); | |
} | |
@end | |
################################################################ | |
//获取已用存储和可用存储 | |
// 获取占用内存 | |
-(void)usedSpaceAndfreeSpace | |
{ | |
NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; | |
NSFileManager* fileManager = [[NSFileManager alloc ]init]; | |
NSDictionary *fileSysAttributes = [fileManager attributesOfFileSystemForPath:path error:nil]; | |
NSNumber *freeSpace = [fileSysAttributes objectForKey:NSFileSystemFreeSize]; | |
NSNumber *totalSpace = [fileSysAttributes objectForKey:NSFileSystemSize]; | |
NSString * str= [NSString stringWithFormat:@"已占用%0.1f G / 剩余%0.1f MB",([totalSpace longLongValue] - [freeSpace longLongValue])/1024.0/1024.0/1024.0,[freeSpace longLongValue]/1024.0/1024.0]; | |
NSLog(@"--------%@",str); | |
} | |
################################################################ | |
计算单个文件大小 | |
+(float)fileSizeAtPath:(NSString *)path{ | |
NSFileManager *fileManager=[NSFileManager defaultManager]; | |
if([fileManager fileExistsAtPath:path]){ | |
long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize; | |
return size/1024.0/1024.0; | |
} | |
return 0; | |
} | |
计算目录大小 | |
+(float)folderSizeAtPath:(NSString *)path{ | |
NSFileManager *fileManager=[NSFileManager defaultManager]; | |
float folderSize; | |
if ([fileManager fileExistsAtPath:path]) { | |
NSArray *childerFiles=[fileManager subpathsAtPath:path]; | |
for (NSString *fileName in childerFiles) { | |
NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; | |
folderSize +=[FileService fileSizeAtPath:absolutePath]; | |
} | |
//SDWebImage框架自身计算缓存的实现 | |
folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0; | |
return folderSize; | |
} | |
return 0; | |
} | |
清理缓存文件 | |
同样也是利用NSFileManager API进行文件操作,SDWebImage框架自己实现了清理缓存操作,我们可以直接调用。 | |
+(void)clearCache:(NSString *)path{ | |
NSFileManager *fileManager=[NSFileManager defaultManager]; | |
if ([fileManager fileExistsAtPath:path]) { | |
NSArray *childerFiles=[fileManager subpathsAtPath:path]; | |
for (NSString *fileName in childerFiles) { | |
//如有需要,加入条件,过滤掉不想删除的文件 | |
NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; | |
[fileManager removeItemAtPath:absolutePath error:nil]; | |
} | |
} | |
[[SDImageCache sharedImageCache] cleanDisk]; | |
} | |
################################################################ | |
iOS开发 之 WebView点击图片看大图效果 | |
http://www.w2bc.com/Article/44789 | |
- (void)webViewDidFinishLoad:(UIWebView *)aWebView { | |
//调整字号 | |
NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '95%'"; | |
[webView stringByEvaluatingJavaScriptFromString:str]; | |
//js方法遍历图片添加点击事件 返回图片个数 | |
static NSString * const jsGetImages = | |
@"function getImages(){\ | |
var objs = document.getElementsByTagName(\"img\");\ | |
for(var i=0;i<objs.length;i++){\ | |
objs[i].onclick=function(){\ | |
document.location=\"myweb:imageClick:\"+this.src;\ | |
};\ | |
};\ | |
return objs.length;\ | |
};"; | |
[webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法 | |
//注入自定义的js方法后别忘了调用 否则不会生效(不调用也一样生效了,,,不明白) | |
NSString *resurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"]; | |
//调用js方法 | |
// NSLog(@"---调用js方法--%@ %s jsMehtods_result = %@",self.class,__func__,resurlt); | |
} | |
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ | |
//将url转换为string | |
NSString *requestString = [[request URL] absoluteString]; | |
// NSLog(@"requestString is %@",requestString); | |
//hasPrefix 判断创建的字符串内容是否以pic:字符开始 | |
if ([requestString hasPrefix:@"myweb:imageClick:"]) { | |
NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length]; | |
// NSLog(@"image url------%@", imageUrl); | |
if (bgView) { | |
//设置不隐藏,还原放大缩小,显示图片 | |
bgView.hidden = NO; | |
imgView.frame = CGRectMake(10, 10, SCREEN_WIDTH-40, 220); | |
[imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:LOAD_IMAGE(@"house_moren")]; | |
} | |
else | |
[self showBigImage:imageUrl];//创建视图并显示图片 | |
return NO; | |
} | |
return YES; | |
} | |
################################################################ | |
NSString * titleText = [NSString stringWithFormat:@"搜索\"%@\"",self.categoryName]; | |
//重点字 | |
NSMutableDictionary *attributes = [NSMutableDictionary new]; | |
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:titleText attributes:attributes]; | |
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.852 green:0.000 blue:0.016 alpha:1.000] range:[attributedString.string rangeOfString:self.categoryName]]; | |
self.naviTitleLabel.attributedText = attributedString; | |
################################################################ | |
字体居左 | |
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; | |
################################################################ | |
-(void) setFade | |
{ | |
_type=kCATransitionFade; | |
} | |
-(void) setCube | |
{ | |
_type=@"cube"; | |
} | |
-(void) setFlip | |
{ | |
_type= @"oglFlip"; | |
} | |
CATransition *transtion = [CATransition animation]; | |
transtion.duration = 0.5; | |
[transtion setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; | |
[transtion setType:_type]; | |
[transtion setSubtype:kCATransitionFromRight]; | |
[view.layer addAnimation:transtion forKey:@"transtionKey"]; | |
[(UIImageView*)view setImage:small]; | |
################################################################ | |
//自动缩放字体 | |
self.priceTotalLabel.adjustsFontSizeToFitWidth = YES; | |
self.priceTotalLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters; | |
################################################################ | |
iOS7 custom leftBarButtonItem 偏移问题 | |
- (void)createNavigationLeftBarButtonItemWithCustomView:(UIButton *)button | |
{ | |
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; | |
if ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7) { | |
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; | |
negativeSpacer.width = -10; | |
self.navigationItem.leftBarButtonItems = @[negativeSpacer, buttonItem]; | |
}else{ | |
self.navigationItem.leftBarButtonItem = buttonItem; | |
} | |
} | |
################################################################ | |
- (id) setNoNull:(id)aValue{ | |
if (aValue == nil) { | |
aValue = @"";//为null时,直接赋空 | |
} else if ((NSNull *)aValue == [NSNull null]) { | |
aValue = @""; | |
if ([aValue isEqual:nil]) { | |
aValue = @""; | |
} | |
} | |
return aValue; | |
} | |
################################################################ | |
定义Block | |
@property (nonatomic, copy, nonnull) dispatch_block_t clickedBlock; | |
typedef void(^MBCClickedSearchBlock)(NSString * _Nullable searchWord); | |
@property (nonatomic, copy, nonnull) MBCClickedSearchBlock clickedSearchBlock; | |
################################################################ | |
// 字体 | |
#define HeitiLight(f) [UIFont fontWithName:@"STHeitiSC-Light" size:f] | |
################################################################ | |
// 设置回调(一旦进入刷新状态,就调用target的action,也就是调用self的loadMoreData方法) | |
MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; | |
// 设置文字 | |
[footer setTitle:@"Click or drag up to refresh" forState:MJRefreshStateIdle]; | |
[footer setTitle:@"Loading more ..." forState:MJRefreshStateRefreshing]; | |
[footer setTitle:@"No more data" forState:MJRefreshStateNoMoreData]; | |
// 设置字体 | |
footer.stateLabel.font = [UIFont systemFontOfSize:17]; | |
// 设置颜色 | |
footer.stateLabel.textColor = [UIColor blueColor]; | |
self.tableView.mj_footer = footer; | |
################################################################ | |
NSDate如何获取一个月后的日期 | |
使用添加月份即可: | |
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; | |
NSDateComponents *comps = nil; | |
comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:mydate]; | |
NSDateComponents *adcomps = [[NSDateComponents alloc] init]; | |
[adcomps setYear:0]; | |
[adcomps setMonth:-1]; | |
[adcomps setDay:0]; | |
NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0]; | |
设置你需要增加或减少的年、月、日即可获得新的日期,上述的表示获取mydate日期前一个月的日期,如果该成+1,则是一个月以后的日期,以此类推都可以计算。 | |
################################################################ | |
Label内容段落间隔 | |
- (void)handleLabel:(UILabel *)cLabel lineSpace:(float)lineSpace{ | |
cLabel.numberOfLines = 0; | |
cLabel.lineBreakMode = NSLineBreakByTruncatingTail; | |
cLabel.textAlignment = NSTextAlignmentLeft; | |
NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc]init]; | |
paragraph.alignment = NSTextAlignmentLeft; //对齐 | |
paragraph.firstLineHeadIndent = 0.0; | |
paragraph.paragraphSpacingBefore = 0.0; | |
paragraph.lineSpacing = lineSpace; | |
paragraph.paragraphSpacing = 8; | |
paragraph.hyphenationFactor = 1.0; | |
paragraph.headIndent = 0; | |
paragraph.tailIndent = 0; | |
NSDictionary *attributest = @{NSParagraphStyleAttributeName : paragraph}; | |
NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:cLabel.text attributes:attributest]; | |
cLabel.attributedText = attributedText; | |
} | |
################################################################ | |
跳转到appstore评分 | |
NSString *reviews = [NSString stringWithFormat:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8",K_MBC_AppStore_ID]; | |
################################################################ | |
程序内显示AppStore信息 | |
@interface ViewController ()<SKStoreProductViewControllerDelegate>{ | |
SKStoreProductViewController *storeProductViewController; | |
} | |
@end | |
@implementation ViewController | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
storeProductViewController = [[SKStoreProductViewController alloc] init]; | |
[storeProductViewController setDelegate:self]; | |
} | |
#pragma mark Store Product View Controller Delegate Methods | |
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController { | |
NSLog(@"操作结束"); | |
[self dismissViewControllerAnimated:YES completion:nil]; | |
} | |
- (IBAction)openStoreAction:(UIButton *)sender { | |
[storeProductViewController loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier :@"1088202830"} completionBlock:^(BOOL result, NSError *error) { | |
if (error) { | |
NSLog(@"Error %@ with User Info %@.", error, [error userInfo]); | |
} else { | |
NSLog(@"正在获取信息"); | |
// Present Store Product View Controller | |
[self presentViewController:storeProductViewController animated:YES completion:nil]; | |
} | |
}]; | |
} | |
################################################################ | |
// 调试函数耗时的利器 | |
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); | |
// do something | |
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent(); | |
NSLog(@"time cost: %0.3f", end - start); | |
################################################################ | |
//Attributed String控制文字 | |
+ (NSMutableAttributedString *)generateAttributedStringFromString:(NSString *)string | |
withFontName:(NSString *)fontName | |
fontSize:(float)fontSize | |
textAlignment:(NSTextAlignment)alignment | |
lineBreakMode:(NSLineBreakMode)lineBreakMode | |
{ | |
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:string]; | |
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; | |
style.lineSpacing = fontSize / 2; | |
style.alignment = alignment; | |
style.lineBreakMode = lineBreakMode; | |
[mutableAttributedString addAttribute:(NSString*)kCTParagraphStyleAttributeName value:style range:NSMakeRange(0, [mutableAttributedString length])]; | |
[mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:fontName size:fontSize] range:NSMakeRange(0, [mutableAttributedString length])]; | |
return mutableAttributedString; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment