讓label的文字內(nèi)容顯示在左上/右上/左下/右下/中心頂/中心底部
自定義UILabel
// 重寫label的textRectForBounds方法
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
switch (self.textAlignmentType) {
case WZBTextAlignmentTypeLeftTop: {
rect.origin = bounds.origin;
}
break;
case WZBTextAlignmentTypeRightTop: {
rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, bounds.origin.y);
}
break;
case WZBTextAlignmentTypeLeftBottom: {
rect.origin = CGPointMake(bounds.origin.x, CGRectGetMaxY(bounds) - rect.size.height);
}
break;
case WZBTextAlignmentTypeRightBottom: {
rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, CGRectGetMaxY(bounds) - rect.size.height);
}
break;
case WZBTextAlignmentTypeTopCenter: {
rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - rect.origin.y);
}
break;
case WZBTextAlignmentTypeBottomCenter: {
rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - CGRectGetMaxY(bounds) - rect.size.height);
}
break;
case WZBTextAlignmentTypeLeft: {
rect.origin = CGPointMake(0, rect.origin.y);
}
break;
case WZBTextAlignmentTypeRight: {
rect.origin = CGPointMake(rect.origin.x, 0);
}
break;
case WZBTextAlignmentTypeCenter: {
rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, (CGRectGetHeight(bounds) - CGRectGetHeight(rect)) / 2);
}
break;
default:
break;
}
return rect;
}
- (void)drawTextInRect:(CGRect)rect {
CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:textRect];
}
1.禁止手機(jī)睡眠
[UIApplication sharedApplication].idleTimerDisabled = YES;
KVO監(jiān)聽某個對象的屬性
// 添加監(jiān)聽者
[self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil];
// 當(dāng)監(jiān)聽的屬性值變化的時(shí)候會來到這個方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"property"]) {
[self textViewTextChange];
} else {
}
}
2.隱藏某行cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 如果是你需要隱藏的那一行,返回高度為0
if(indexPath.row == YouWantToHideRow)
return 0;
return 44;
}
// 然后再你需要隱藏cell的時(shí)候調(diào)用
[self.tableView beginUpdates];
[self.tableView endUpdates];
15、跳進(jìn)app權(quán)限設(shè)置
// 跳進(jìn)app設(shè)置
if (UIApplicationOpenSettingsURLString != NULL) {
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url];
}
}
16、給一個view截圖
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
17、開發(fā)中如果要動態(tài)修改tableView的tableHeaderView或者tableFooterView的高度,需要給tableView重新設(shè)置,而不是直接更改高度。正確的做法是重新設(shè)置一下tableView.tableFooterView = 更改過高度的view。為什么?其實(shí)在iOS8以上直接改高度是沒有問題的,在iOS8中出現(xiàn)了contentSize不準(zhǔn)確的問題,這是解決辦法。
20、設(shè)置navigationBar上的title顏色和大小
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}]
22、view設(shè)置圓角
#define ViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]] // view圓角
26、獲取圖片資源
#define GetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]
36、通知
#define NOTIF_ADD(n, f) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(f) name:n object:nil]
#define NOTIF_POST(n, o) [[NSNotificationCenter defaultCenter] postNotificationName:n object:o]
#define NOTIF_REMV() [[NSNotificationCenter defaultCenter] removeObserver:self]
37、隨機(jī)顏色
+ (UIColor *)RandomColor {
NSInteger aRedValue = arc4random() % 255;
NSInteger aGreenValue = arc4random() % 255;
NSInteger aBlueValue = arc4random() % 255;
UIColor *randColor = [UIColor colorWithRed:aRedValue / 255.0f green:aGreenValue / 255.0f blue:aBlueValue / 255.0f alpha:1.0f];
return randColor;
}
39、修改textField的placeholder的字體顏色、大小
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
42、獲取app緩存大小
- (CGFloat)getCachSize {
NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
//獲取自定義緩存大小
//用枚舉器遍歷 一個文件夾的內(nèi)容
//1.獲取 文件夾枚舉器
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
__block NSUInteger count = 0;
//2.遍歷
for (NSString *fileName in enumerator) {
NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
count += fileDict.fileSize;//自定義所有緩存大小
}
// 得到是字節(jié) 轉(zhuǎn)化為M
CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
return totalSize;
}
43、清理app緩存
- (void)handleClearView {
//刪除兩部分
//1.刪除 sd 圖片緩存
//先清除內(nèi)存中的圖片緩存
[[SDImageCache sharedImageCache] clearMemory];
//清除磁盤的緩存
[[SDImageCache sharedImageCache] clearDisk];
//2.刪除自己緩存
NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
[[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
}
47、幾個常用權(quán)限判斷
if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
NSLog(@"沒有定位權(quán)限");
}
AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (statusVideo == AVAuthorizationStatusDenied) {
NSLog(@"沒有攝像頭權(quán)限");
}
//是否有麥克風(fēng)權(quán)限
AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (statusAudio == AVAuthorizationStatusDenied) {
NSLog(@"沒有錄音權(quán)限");
}
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusDenied) {
NSLog(@"沒有相冊權(quán)限");
}
}];
49、長按復(fù)制功能
- (void)viewDidLoad
{
[self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]];
}
- (void)pasteBoard:(UILongPressGestureRecognizer *)longPress {
if (longPress.state == UIGestureRecognizerStateBegan) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = @"需要復(fù)制的文本";
}
}
55、image圓角
- (UIImage *)circleImage
{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
// 獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加一個圓
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
// 方形變圓形
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 將圖片畫上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
image拉伸
+ (UIImage *)resizableImage:(NSString *)imageName
{
UIImage *image = [UIImage imageNamed:imageName];
CGFloat imageW = image.size.width;
CGFloat imageH = image.size.height;
return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];
}
57、JSON字符串轉(zhuǎn)字典
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
return responseJSON;
}
61、拿到當(dāng)前正在顯示的控制器,不管是push進(jìn)去的,還是present進(jìn)去的都能拿到
- (UIViewController *)getVisibleViewControllerFrom:(UIViewController*)vc {
if ([vc isKindOfClass:[UINavigationController class]]) {
return [self getVisibleViewControllerFrom:[((UINavigationController*) vc) visibleViewController]];
}else if ([vc isKindOfClass:[UITabBarController class]]){
return [self getVisibleViewControllerFrom:[((UITabBarController*) vc) selectedViewController]];
} else {
if (vc.presentedViewController) {
return [self getVisibleViewControllerFrom:vc.presentedViewController];
} else {
return vc;
}
}
}
71、根據(jù)bundle中的文件名讀取圖片
+ (UIImage *)imageWithFileName:(NSString *)name {
NSString *extension = @"png";
NSArray *components = [name componentsSeparatedByString:@"."];
if ([components count] >= 2) {
NSUInteger lastIndex = components.count - 1;
extension = [components objectAtIndex:lastIndex];
name = [name substringToIndex:(name.length-(extension.length+1))];
}
// 如果為Retina屏幕且存在對應(yīng)圖片,則返回Retina圖片,否則查找普通圖片
if ([UIScreen mainScreen].scale == 2.0) {
name = [name stringByAppendingString:@"@2x"];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
if (path != nil) {
return [UIImage imageWithContentsOfFile:path];
}
}
if ([UIScreen mainScreen].scale == 3.0) {
name = [name stringByAppendingString:@"@3x"];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
if (path != nil) {
return [UIImage imageWithContentsOfFile:path];
}
}
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
if (path) {
return [UIImage imageWithContentsOfFile:path];
}
return nil;
}
73、根據(jù)bundle中的圖片名創(chuàng)建imageview
+ (id)imageViewWithImageNamed:(NSString*)imageName
{
return [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
}
cell去除選中效果
cell.selectionStyle = UITableViewCellSelectionStyleNone;
106、禁用系統(tǒng)滑動返回功能
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return NO;
}
109、UILabel設(shè)置內(nèi)邊距
子類化UILabel,重寫drawTextInRect方法
- (void)drawTextInRect:(CGRect)rect {
// 邊距,上左下右
UIEdgeInsets insets = {0, 5, 0, 5};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
117、將一個view放置在其兄弟視圖的最上面
1
[parentView bringSubviewToFront:yourView]
118、將一個view放置在其兄弟視圖的最下面
1
[parentView sendSubviewToBack:yourView]
122、搖一搖功能
1、打開搖一搖功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
2、讓需要搖動的控制器成為第一響應(yīng)者
[self becomeFirstResponder];
3、實(shí)現(xiàn)以下方法
// 開始搖動
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
// 取消搖動
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
// 搖動結(jié)束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
132、設(shè)置tableView分割線顏色
[self.tableView setSeparatorColor:[UIColor myColor]];
135、tableViewCell分割線頂?shù)筋^
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setLayoutMargins:UIEdgeInsetsZero];
cell.preservesSuperviewLayoutMargins = NO;
}
- (void)viewDidLayoutSubviews {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
139、在狀態(tài)欄增加網(wǎng)絡(luò)請求的菊花,類似safari加載網(wǎng)頁的時(shí)候狀態(tài)欄菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;