1.NSTimer
//暫停
if ([timer isValid]) {
[timer setFireDate:[NSDate distantFuture]];
}
//恢復
NSDate * date = [NSDate date];
[timer setFireDate:date];
//在離開界面或者計時器不在使用的時候一定要調用invalidate方法婿斥,不然會導致內存泄露
[timer invalidate];
2.UITabBarItem 圖片設置
//如果這么設置的圖片會被tabbarItem 所在的tabbar的tintColor所渲染氓英。所以得到不原圖
UITabBarItem *item = [[UITabBarItem alloc]init];
item.image = [UIImage imageNamed:@"norImg"];
item.selectedImage = [UIImage imageNamed:@"selImg"];
//解決方案
UITabBarItem *item = [[UITabBarItem alloc]init];
item.image = [[UIImage imageNamed:@"norImg"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
item.selectedImage = [[UIImage imageNamed:@"selImg"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
3.圖像拉伸 - (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
//在開發(fā)過程中經常會遇到圖片大小不確定湖蜕,但是如果圖片部分拉伸后能滿足的情況。這時候可以使用系統(tǒng)自帶圖片拉伸函數。
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
leftCapWidth 可以理解為x
topCapHeight 理解為y
意思就是水平方向以x垂線為基準開始拉伸集乔,拉伸的只是x垂線其他的不變,可以把x垂線想象成一個1像素的寬度高度和圖片一樣的線條,把一個線拉伸成一個很粗的線條郭变。
垂直方向同理。
4.UIWebView Http頭設置
//UIWebView Http頭設置有兩種方式
//1.實現UIWebViewDelegate的
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//在這里寫一些代碼涯保,判斷NSURLRequest的請求頭是否合乎要求诉濒,不合則讓webview加載修改夠的NSURLRequest,并返回NO
//例如:
NSString *ua = request.allHTTPHeaderFields[@"User-Agent"];
if (![ua isEqualToString:@"HHURLProtocolDome/1.0.0"]) {
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest setValue:@"HHURLProtocolDome/1.0.0" forHTTPHeaderField:@"User-Agent"];
[webView loadRequest:mutableRequest];
return NO;
}
return YES;
}
//2.繼承NSURLProtocol并重寫其方法
static NSString *kUserAgent = @"User-Agent";
static NSString *kPropertyKey = @"kPropertyKey";
@interface HHURLProtocol()<NSURLSessionDataDelegate,NSURLSessionTaskDelegate,NSURLSessionDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionTask *task;
@end
@implementation HHURLProtocol
- (NSURLSession *)session{
if (_session == nil) {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.protocolClasses = @[[self class]];
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
}
return _session;
}
(void)load{
[NSURLProtocol registerClass:[HHURLProtocol class]];
}(BOOL)canInitWithRequest:(NSURLRequest *)request{
return [self checkRequest:request];
}-
(NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request{
return [self settingHttpHeader:request];
}
(void)startLoading
{
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
[NSURLProtocol setProperty:@YES forKey:kPropertyKey inRequest:mutableReqeust];
_task = [self.session dataTaskWithRequest:mutableReqeust];
[_task resume];
}(void)stopLoading
{
[_task cancel];
}
pragma mark - NSURLSessionDataDelegate
-
(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler{[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[self.client URLProtocol:self didLoadData:data];
}
pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (!error) {
[self.client URLProtocolDidFinishLoading:self];
}
else {
[self.client URLProtocol:self didFailWithError:error];
}
}
pragma mark - check request
(BOOL)checkRequest:(NSURLRequest *)request{
if ([NSURLProtocol propertyForKey:kPropertyKey inRequest:request]) {
return NO;
}
return YES;//通過
}(NSURLRequest *)settingHttpHeader:(NSURLRequest *)request{
NSMutableURLRequest *mutableReqeust = [request mutableCopy];
[mutableReqeust setValue:@"HHURLProtocolDome/1.0.0" forHTTPHeaderField:kUserAgent];
return mutableReqeust;
}
@end
//方法2附上demo一份 https://github.com/MRCaoHH/HHURLProtocolDome
//老問題了夕春,demo又打錯......
5.虛線邊框
.h
import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger,HHDottedLineDirection){
HHDottedLineDirection_Top = 1,
HHDottedLineDirection_Left = 1 << 1,
HHDottedLineDirection_Bottom = 1 << 2,
HHDottedLineDirection_Right = 1 << 3
};
@interface UIView (HHCategory)
@property (nonatomic,assign) CGPoint origin;
@property (nonatomic,assign) CGSize size;
@property (nonatomic,assign) CGFloat width;
@property (nonatomic,assign) CGFloat height;
@property (nonatomic,assign) CGFloat y;
@property (nonatomic,assign) CGFloat x;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;
@property (nonatomic,assign) CGFloat bottom;
@property (nonatomic,assign) CGFloat top;
@property (nonatomic,assign) CGFloat left;
@property (nonatomic,assign) CGFloat right;
/**
- @brief 繪制虛線
- @param direction 方向
- @param color 顏色
- @param lineDashPattern 虛線連續(xù)長度
- @param lineWidth 線條粗細
*/
- (void)drawDottedLine:(HHDottedLineDirection)direction lineColor:(UIColor *)color lineDashPattern:(NSArray <NSNumber >)lineDashPattern lineWidth:(CGFloat)lineWidth;
/**
- @brief 繪制圓角虛線邊框
- @param lineColor 顏色
- @param lineDashPattern 虛線連續(xù)長度
- @param lineWidth 線條粗細
*/
- (void)drawDottedLineCornerRadius:(UIColor *)lineColor lineDashPattern:(NSArray <NSNumber >)lineDashPattern lindWidth:(CGFloat)lineWidth ;
@end
.m
@implementation UIView (HHCategory)
pragma mark - origin 坐標點
-(CGPoint)origin
{
return self.frame.origin;
}
-(void)setOrigin:(CGPoint)origin
{
CGRect frame = self.frame;
frame.origin = origin;
self.frame = frame;
}
pragma mark - size 大小
-(CGSize)size
{
return self.frame.size;
}
-(void)setSize:(CGSize)size
{
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
pragma mark - width 寬度
-(CGFloat)width
{
return self.size.width;
}
-(void)setWidth:(CGFloat)width
{
CGSize size = self.size;
size.width = width;
self.size = size;
}
pragma mark - height 高度
-(CGFloat)height
{
return self.size.height;
}
-(void)setHeight:(CGFloat)height
{
CGSize size = self.size;
size.height = height;
self.size = size;
}
pragma mark - x 橫坐標
-(CGFloat)x
{
return self.origin.x;
}
-(void)setX:(CGFloat)x
{
CGPoint origin = self.origin;
origin.x = x;
self.origin = origin;
}
pragma mark - y 縱坐標
-(CGFloat)y
{
return self.origin.y;
}
-(void)setY:(CGFloat)y
{
CGPoint origin = self.origin;
origin.y = y;
self.origin = origin;
}
(void)setCenterX:(CGFloat)centerX
{
CGPoint center = self.center;
center.x = centerX;
self.center = center;
}(CGFloat)centerX
{
return self.center.x;
}(CGFloat)left {
return self.frame.origin.x;
}(void)setLeft:(CGFloat)x {
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}(void)setCenterY:(CGFloat)centerY
{
CGPoint center = self.center;
center.y = centerY;
self.center = center;
}(CGFloat)centerY
{
return self.center.y;
}(void)setTop:(CGFloat)y {
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}(CGFloat)top {
return self.frame.origin.y;
}(void)setBottom:(CGFloat)bottom {
CGRect frame = self.frame;
frame.origin.y = bottom - frame.size.height;
self.frame = frame;
}(CGFloat)bottom {
return self.frame.origin.y + self.frame.size.height;
}(CGFloat)right {
return self.frame.origin.x + self.frame.size.width;
}(void)setRight:(CGFloat)right {
CGRect frame = self.frame;
frame.origin.x = right - frame.size.width;
self.frame = frame;
}-
(void)drawDottedLine:(HHDottedLineDirection)direction lineColor:(UIColor *)color lineDashPattern:(NSArray <NSNumber >)lineDashPattern lineWidth:(CGFloat)lineWidth{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = CGRectMake(0, 0, self.width, self.height);
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
//設置虛線顏色
[shapeLayer setStrokeColor:[color CGColor]];
//設置虛線的寬度
[shapeLayer setLineWidth:lineWidth];
[shapeLayer setLineJoin:kCALineJoinRound];
//設置虛線線段
[shapeLayer setLineDashPattern:[NSArray arrayWithArray:lineDashPattern]];// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
if (direction & HHDottedLineDirection_Top) {
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, self.width, 0);
}if (direction & HHDottedLineDirection_Right) {
CGPathMoveToPoint(path, NULL, self.width - lineWidth, 0);
CGPathAddLineToPoint(path, NULL, self.width - lineWidth, self.height);
}if (direction & HHDottedLineDirection_Bottom) {
CGPathMoveToPoint(path, NULL, 0, self.height - lineWidth);
CGPathAddLineToPoint(path, NULL, self.width , self.height - lineWidth);
}if (direction & HHDottedLineDirection_Left) {
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, 0, self.height);
}[shapeLayer setPath:path];
CGPathRelease(path);
[self.layer addSublayer:shapeLayer];
} -
(void)drawDottedLineCornerRadius:(UIColor *)lineColor lineDashPattern:(NSArray <NSNumber >)lineDashPattern lindWidth:(CGFloat)lineWidth{
//圓角
CGFloat cornerRadius = self.layer.cornerRadius;
CGFloat borderWidth = lineWidth;CGRect frame = self.bounds;
CAShapeLayer *shapeLayer = [CAShapeLayer layer];CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0, frame.size.height - cornerRadius);
CGPathAddLineToPoint(path, NULL, 0, cornerRadius);
CGPathAddArc(path, NULL, cornerRadius, cornerRadius, cornerRadius, M_PI, -M_PI_2, NO);
CGPathAddLineToPoint(path, NULL, frame.size.width - cornerRadius, 0);
CGPathAddArc(path, NULL, frame.size.width - cornerRadius, cornerRadius, cornerRadius, -M_PI_2, 0, NO);
CGPathAddLineToPoint(path, NULL, frame.size.width, frame.size.height - cornerRadius);
CGPathAddArc(path, NULL, frame.size.width - cornerRadius, frame.size.height - cornerRadius, cornerRadius, 0, M_PI_2, NO);
CGPathAddLineToPoint(path, NULL, cornerRadius, frame.size.height);
CGPathAddArc(path, NULL, cornerRadius, frame.size.height - cornerRadius, cornerRadius, M_PI_2, M_PI, NO);//path is set as the _shapeLayer object's path
shapeLayer.path = path;
CGPathRelease(path);shapeLayer.backgroundColor = [[UIColor clearColor] CGColor];
shapeLayer.frame = frame;
shapeLayer.masksToBounds = NO;
[shapeLayer setValue:[NSNumber numberWithBool:NO] forKey:@"isCircle"];
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
shapeLayer.strokeColor = [lineColor CGColor];
shapeLayer.lineWidth = borderWidth;
shapeLayer.lineDashPattern = lineDashPattern;
shapeLayer.lineCap = kCALineCapRound;[self.layer addSublayer:shapeLayer];
}
@end
6.今天周幾未荒,本月有多少天,今年是否是閏年
內容源自rfc3339
//rfc3339
//根據日期得到周幾
int dayOfWeek(int day, int month, int year)
{
int cent;
int dayofweek[] = {
7, 1, 2, 3,
4, 5, 6
};
/* adjust months so February is the last one */
month -= 2;
if (month < 1) {
month += 12;
--year;
}
/* split by century */
cent = year / 100;
year %= 100;
return (dayofweek[((26 * month - 2) / 10 + day + year
+ year / 4 + cent / 4 + 5 * cent) % 7]);
}
//根據年月得到當月的總天數
int monthDayCount(int year, int month){
//01 January 31
//02 February, normal 28
//03 March 31
//04 April 30
//05 May 31
//06 June 30
//07 July 31
//08 August 31
//09 September 30
//10 October 31
//11 November 30
//12 December 31
//02 February, leap year 29
///驗證月份及志,在1~12之間
if (month < 1 || month > 12) {
return 0;
}
int arr[] = {31,28,31,30,31,30,31,31,30,31,30,31,29};
int index = month - 1;
if ( leapYear(year) && month == 2) {
index = 12;
}
return arr[index];
}
//是否是閏年
int leapYear(int year){
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
如果你更喜歡oc或者swift可以嘗試將以上代碼轉成你喜歡的片排,接下來介紹下用日歷實現方法:
//當月的天數
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
NSLog(@"%@",NSStringFromRange(range));
//當前時間周幾,注意周一
NSInteger week = [calendar component:NSCalendarUnitWeekday fromDate:[NSDate date]];
NSLog(@"%zd",week);
//閏年,方法多樣,可以用- (NSInteger)component:(NSCalendarUnit)unit fromDate:(NSDate *)date方法得到當年的天數做判斷也可以直接用年份計算速侈,故此略
7.TableViewCell點擊的時候改變cell上控件背景顏色問題
(void)setSelected:(BOOL)selected animated:(BOOL)animated{
//在這里直接設置背景顏色
}(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
//在這里直接設置背景顏色
}
8.攝像頭檢測
if(![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]){
//前邊攝像頭不可用
}
if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
//后邊攝像頭不可用的代碼
}
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
//攝像頭不可用
}
9.約束動畫
[containerView layoutIfNeeded];
[UIView animateWithDuration:1.0 animations:^{
// Make all constraint changes here
[containerView layoutIfNeeded];
}];
10.textFiled 占位文本顏色
//1.直接設置屬性字符串
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 20, 375, 44)];
textField.backgroundColor = [UIColor whiteColor];
NSAttributedString *attString = [[NSAttributedString alloc]initWithString:@"占位符" attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
textField.attributedPlaceholder = attString;
[self.view addSubview:textField];
//2.利用私有字段
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
11.textView 占位文本實現
UITextView+HHCategory.h
import <UIKit/UIKit.h>
@interface UITextView (HHCategory)
@property (nonatomic, strong) NSString *placeholder;
@property (nonatomic, strong) UIColor *placeholderColor;
@property (nonatomic, strong) NSAttributedString *attributedPlaceholder;
@end
UITextView+HHCategory.m
import "UITextView+HHCategory.h"
import <objc/runtime.h>
@implementation NSObject (HHCategory)
(void)HH_SwizzleClassMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
Method otherMehtod = class_getClassMethod(class, otherSelector);
Method originMehtod = class_getClassMethod(class, originSelector);
// 交換2個方法的實現
method_exchangeImplementations(otherMehtod, originMehtod);
}(void)HH_SwizzleInstanceMethod:(Class)class originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector
{
Method otherMehtod = class_getInstanceMethod(class, otherSelector);
Method originMehtod = class_getInstanceMethod(class, originSelector);
// 交換2個方法的實現
method_exchangeImplementations(otherMehtod, originMehtod);
}
@end
@implementation UITextView (HHCategory)
@dynamic placeholder,attributedPlaceholder,placeholderColor;
(UIColor *)HH_DefaultPlaceholderColor {
static UIColor *color = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
UITextField *textField = [[UITextField alloc] init];
textField.placeholder = @" ";
color = [textField valueForKeyPath:@"_placeholderLabel.textColor"];
});
return color;
}(void)load{
[self HH_SwizzleInstanceMethod:self originSelector:NSSelectorFromString(@"dealloc") otherSelector:@selector(HH_Dealloc)];
}
(void)HH_Dealloc{
[self HH_RemoveNotification];
[self HH_RemoveServer];
[self HH_Dealloc];
}(UIColor *)placeholderColor{
UIColor *placeholderColor = objc_getAssociatedObject(self, @selector(placeholderColor));
if (placeholderColor == nil) {
return [UITextView HH_DefaultPlaceholderColor];
}
return objc_getAssociatedObject(self, @selector(placeholderColor));
}(void)setPlaceholderColor:(UIColor *)placeholderColor{
objc_setAssociatedObject(self, @selector(placeholderColor), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self updatePlaceholder];
}(NSString *)placeholder{
return objc_getAssociatedObject(self, @selector(placeholder));
}(void)setPlaceholder:(NSString *)placeholder{
objc_setAssociatedObject(self, @selector(placeholder), placeholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self updatePlaceholder];
}(NSAttributedString *)attributedPlaceholder{
return objc_getAssociatedObject(self, @selector(attributedPlaceholder));
}(void)setAttributedPlaceholder:(NSAttributedString *)attributedPlaceholder{
objc_setAssociatedObject(self, @selector(attributedPlaceholder), attributedPlaceholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self updatePlaceholder];
}(UILabel *)placeholderLabel{
return objc_getAssociatedObject(self, @selector(placeholderLabel));
}(void)setPlaceholderLabel:(UILabel *)placeholderLabel{
objc_setAssociatedObject(self, @selector(placeholderLabel), placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}-
(void)updatePlaceholder{
if( [self.placeholder length] > 0 && self.text.length == 0)
{
if (self.placeholderLabel == nil )
{
self.placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.textContainerInset.left,self.textContainerInset.top,self.bounds.size.width ,0)];
self.placeholderLabel.numberOfLines = 0;
self.placeholderLabel.backgroundColor = [UIColor clearColor];
self.placeholderLabel.alpha = 0;
self.placeholderLabel.font = self.font;
self.placeholderLabel.textColor = self.placeholderColor;
[self addSubview:self.placeholderLabel];
self.text = @" ";
self.text = @"";
[self HH_AddNotification];
[self HH_AddObServer];
}self.placeholderLabel.frame = CGRectMake(self.textContainer.lineFragmentPadding,self.textContainerInset.top,self.bounds.size.width ,0); self.placeholderLabel.textAlignment = self.textAlignment; self.placeholderLabel.font = self.font; self.placeholderLabel.textColor = self.placeholderColor; if (self.attributedPlaceholder == nil) { self.placeholderLabel.text = self.placeholder; }else{ self.placeholderLabel.attributedText = self.attributedPlaceholder; } [self.placeholderLabel sizeToFit]; [self sendSubviewToBack:self.placeholderLabel];
}
self.placeholderLabel.alpha = ([[self text] length] == 0);
} (void)HH_AddNotification{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlaceholder) name:UITextViewTextDidChangeNotification object:nil];
}(void)HH_RemoveNotification{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}(void)HH_AddObServer{
NSArray *keys = [self HH_ObServerKey];
for (NSString *obKey in keys) {
[self addObserver:self forKeyPath:obKey options:NSKeyValueObservingOptionNew context:nil];
}
}
- (void)HH_RemoveServer{
NSArray *keys = [self HH_ObServerKey];
for (NSString *obKey in keys) {
[self removeObserver:self forKeyPath:obKey];
}
}
(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSArray *keys = [self HH_ObServerKey];
if ([keys containsObject:keyPath]) {
[self updatePlaceholder];
}
}(NSArray *)HH_ObServerKey {
return @[@"attributedText",
@"bounds",
@"font",
@"frame",
@"text",
@"textAlignment",
@"textContainerInset"];
}
@end
12.分割線
UITableView的類型有兩種UITableViewStylePlain和UITableViewStyleGrouped
Plain類型是沒有包邊線的
UITableViewStylePlain
Grouped是存在包邊線的率寡。
UITableViewStyleGrouped
根據自己的需求選擇合適的類型
//設置tableView的style,只有初始化的時候能設置
UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
//分割線的位置調整
tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
//分割線顏色
tableView.separatorColor = [UIColor redColor];
//cell也能調整分割線位置
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier];
if(!cell){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: identifier];
}
cell.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
13.系統(tǒng)版本判斷宏
獲取當前設備系統(tǒng)版本代碼如下:
//獲取的到值是字符串倚搬,例如iOS10獲取到的版本號是10.0
[UIDevice currentDevice].systemVersion
判斷系統(tǒng)版本大于小于的宏可以這么寫:
//系統(tǒng)版本大于小于的宏
define k_Check_iOS(x) [UIDevice currentDevice].systemVersion.floatValue > x
如果要更精確的判斷系統(tǒng)的版本就更麻煩一些了冶共,在iOS里面已經定義了一些系統(tǒng)版本號的宏,如下:
define __IPHONE_2_0 20000
define __IPHONE_2_1 20100
define __IPHONE_2_2 20200
define __IPHONE_3_0 30000
define __IPHONE_3_1 30100
define __IPHONE_3_2 30200
define __IPHONE_4_0 40000
define __IPHONE_4_1 40100
define __IPHONE_4_2 40200
define __IPHONE_4_3 40300
define __IPHONE_5_0 50000
define __IPHONE_5_1 50100
define __IPHONE_6_0 60000
define __IPHONE_6_1 60100
define __IPHONE_7_0 70000
define __IPHONE_7_1 70100
define __IPHONE_8_0 80000
define __IPHONE_8_1 80100
define __IPHONE_8_2 80200
define __IPHONE_8_3 80300
define __IPHONE_8_4 80400
define __IPHONE_9_0 90000
define __IPHONE_9_1 90100
define __IPHONE_9_2 90200
define __IPHONE_9_3 90300
define __IPHONE_10_0 100000
判斷宏如下
define kOSVersion ({\
NSArray version = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
NSInteger versionNum = 0;
if ([version count] > 0) {
versionNum += [version[0] integerValue] * 10000;
}
if ([version count] > 1) {
versionNum += [version[1] integerValue] 100;
}
if ([version count] > 2) {
versionNum += [version[2] integerValue];
}
versionNum;
})
define k_Is_iOS7_1 __IPHONE_7_1 == kOSVersion
define k_Is_iOS8_0 __IPHONE_8_0 == kOSVersion
define k_Is_iOS8_1 __IPHONE_8_1 == kOSVersion
define k_Is_iOS8_2 __IPHONE_8_2 == kOSVersion
define k_Is_iOS8_3 __IPHONE_8_3 == kOSVersion
define k_Is_iOS8_4 __IPHONE_8_4 == kOSVersion
define k_Is_iOS9_0 __IPHONE_9_0 == kOSVersion
define k_Is_iOS9_1 __IPHONE_9_1 == kOSVersion
define k_Is_iOS9_2 __IPHONE_9_2 == kOSVersion
define k_Is_iOS9_3 __IPHONE_9_3 == kOSVersion
define k_Is_iOS10_0 __IPHONE_10_0 == kOSVersion
14.時間格式 YYYY/MM/DD HH:mm:ss
/ 日期分隔符
: 時間分隔符
d 顯示日每界,小于10的時候前面不帶0
dd 顯示日捅僵,小于10的時候前面帶0
EEE 將日顯示為縮寫形式(例如 Sun)。
EEEE 將日顯示為全名(例如 Sunday)眨层。
M 將月份顯示為不帶前導零的數字(如一月表示為 1)庙楚。如果這是用戶定義的數字格式中的唯一字符,請使用 %M趴樱。
MM 將月份顯示為帶前導零的數字(例如 01/12/01)馒闷。
MMM 將月份顯示為縮寫形式(例如 Jan)酪捡。
MMMM 將月份顯示為完整月份名(例如 January)。
gg 顯示時代/紀元字符串(例如 A.D.)
h 使用 12 小時制將小時顯示為不帶前導零的數字(例如 1:15:15 PM)窜司。如果這是用戶定義的數字格式中的唯一字符沛善,請使用 %h。
hh 使用 12 小時制將小時顯示為帶前導零的數字(例如 01:15:15 PM)塞祈。
H 使用 24 小時制將小時顯示為不帶前導零的數字(例如 1:15:15)金刁。如果這是用戶定義的數字格式中的唯一字符,請使用 %H议薪。
HH 使用 24 小時制將小時顯示為帶前導零的數字(例如 01:15:15)尤蛮。
m 將分鐘顯示為不帶前導零的數字(例如 12:1:15)。如果這是用戶定義的數字格式中的唯一字符斯议,請使用 %m产捞。
mm 將分鐘顯示為帶前導零的數字(例如 12:01:15)。
s 將秒顯示為不帶前導零的數字(例如 12:15:5)哼御。如果這是用戶定義的數字格式中的唯一字符坯临,請使用 %s。
ss 將秒顯示為帶前導零的數字(例如 12:15:05)恋昼。
f 顯示秒的小數部分看靠。例如,ff 將精確顯示到百分之一秒液肌,而 ffff 將精確顯示到萬分之一秒挟炬。用戶定義格式中最多可使用七個 f 符號。如果這是用戶定義的數字格式中的唯一字符嗦哆,請使用 %f谤祖。
t 使用 12 小時制,并對中午之前的任一小時顯示大寫的 A老速,對中午到 11:59 P.M 之間的任一小時顯示大寫的 P粥喜。如果這是用戶定義的數字格式中的唯一字符,請使用 %t橘券。
tt 對于使用 12 小時制的區(qū)域設置容客,對中午之前任一小時顯示大寫的 AM,對中午到 11:59 P.M 之間的任一小時顯示大寫的 PM约郁。對于使用 24 小時制的區(qū)域設置,不顯示任何字符但两。
y 將年份 (0-9) 顯示為不帶前導零的數字鬓梅。如果這是用戶定義的數字格式中的唯一字符,請使用 %y谨湘。
yy 以帶前導零的兩位數字格式顯示年份绽快。
yyy 以四位數字格式顯示年份芥丧。
yyyy 以四位數字格式顯示年份。
z 顯示不帶前導零的時區(qū)偏移量(如 -8)坊罢。如果這是用戶定義的數字格式中的唯一字符续担,請使用 %z。
zz 顯示帶前導零的時區(qū)偏移量(例如 -08)
zzz 顯示完整的時區(qū)偏移量(例如 -08:00)
15.PrefixHeader.pch文件添加
- 創(chuàng)建文件 .pch文件(commoand + N -> Othe -> PCH File )
- 設置PrefixHeader路徑(選中Target -> Build Settings ->Prefix Header)
16.use of '@import' when modules are disabled
首先設置選中Target -> Build Settings -> Enable Module (C and Objective-C) 為YES
如果不行活孩,請檢查在導入的該頭文件的文件格式是否為.mm(編譯c++的文件物遇,例如百度地圖需要把AppDelegate.m改成AppDelegate.mm)文件。
17.iOS 推送
本地推送憾儒。
iOS10以前
-
(void)post_Less_iOS10:(NSDictionary *)userInfo title:(NSString *)title body:(NSString *)body{
UILocalNotification *notification = [[UILocalNotification alloc] init];
// 設置觸發(fā)通知的時間询兴,這里設置的是立即觸發(fā)
NSDate *fireDate = [NSDate date];
notification.fireDate = fireDate;// 通知內容
notification.alertBody = body;
//標題,iOS8.2之后才有了這個屬性
if ([notification respondsToSelector:@selector(setAlertTitle:)]) {
notification.alertTitle = title;
}// 通知的聲音
notification.soundName = UILocalNotificationDefaultSoundName;
//附帶內容
notification.userInfo = userInfo;// ios8后起趾,需要添加這個注冊诗舰,才能得到授權
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
///設置
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}// 執(zhí)行通知注冊
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
AppDelegate.m (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {//app在前臺
NSLog(@"app在前臺");
}else{//不在前臺
NSLog(@"app不在前臺");
}
}
iOS10之后(void)registerNoti{
// iOS10 兼容
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
// 使用 UNUserNotificationCenter 來管理通知
UNUserNotificationCenter *uncenter = [UNUserNotificationCenter currentNotificationCenter];
// 監(jiān)聽回調事件
[uncenter setDelegate:self];
//iOS10 使用以下方法注冊,才能得到授權
[uncenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert+UNAuthorizationOptionBadge+UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
NSLog(@"%@" , granted ? @"授權成功" : @"授權失敗");
}];
// 獲取當前的通知授權狀態(tài), UNNotificationSettings
[uncenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
NSLog(@"未選擇");
} else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
NSLog(@"未授權");
} else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
NSLog(@"已授權");
}
}];
}
}-
(void)post_iOS10:(NSDictionary *)userInfo title:(NSString *)title body:(NSString *)body{
// 使用 UNUserNotificationCenter 來管理通知
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];//需創(chuàng)建一個包含待通知內容的 UNMutableNotificationContent 對象训裆,注意不是 UNNotificationContent ,此對象為不可變對象眶根。
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:title arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:body
arguments:nil];
content.sound = [UNNotificationSound defaultSound];content.userInfo = userInfo;
// 在 alertTime 后推送本地推送
UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:1 repeats:NO];UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
content:content trigger:trigger];//添加推送成功后的處理!
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
}
pragma mark - UNUserNotificationCenterDelegate
///在前臺接收到通知
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
completionHandler(UNNotificationPresentationOptionAlert);//不寫這句通知不會出現在前臺边琉,如有需要|UNNotificationPresentationOptionSound属百,角標UNNotificationPresentationOptionBadge
}
///點擊通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
//handle touch event
}
上面代碼可以寫在appdelegate里面,或者一個單例艺骂。registerNoti 方法在發(fā)送前或者app啟動的時候調用诸老。
注意iOS10之前本地通知在app處于前臺的時候是不會出現的,有時或者有些產品需要這樣的功能钳恕,故此只能自己做個類似通知一樣的東西别伏,在這里推薦個EBForeNotification。
18.首字母獲取
- (NSString *)getFirstChat:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef) str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pinYin = [str capitalizedString];
return [pinYin substringToIndex:1];
}
19.狀態(tài)欄
1.啟動的時候隱藏狀態(tài)欄
info.plist 設置字段Status bar is initially hidden 為YES
2.狀態(tài)欄顏色為白色UIStatusBarStyleLightContent
info.plist 設置字段Status bar style為YES
3.關于View controller-based status bar appearance
//如果View controller-based status bar appearance的值是YES忧额,那么程序中要改變狀態(tài)欄顏色只能設置整個app的狀態(tài)厘肮,單獨設置某個VC是不行的也就是說UIViewController的下面兩個方法失效:
- (UIStatusBarStyle)preferredStatusBarStyle;
-(BOOL)prefersStatusBarHidden;
4.刷新當前VC的狀態(tài)欄
//info.plist文件中不能含有View controller-based status bar appearance
[self setNeedsStatusBarAppearanceUpdate];
20.導航欄背景顏色
//這里調用到了下面的顏色生成圖片的方法
UIImage *img = [UIImage HH_CreateImageFromColor:color];
[self.navigationBar setBackgroundImage: img forBarMetrics:UIBarMetricsDefault];
//設置陰影,如果不設置導航欄下面有條黑線
[self.navigationBar setShadowImage:img];
21.顏色生成圖片
pragma mark - 根據顏色和大小生產圖片
- (UIImage *)HH_CreateImageFromColor:(UIColor *)color size:(CGSize)size
{
CGRect imageRect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(imageRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, imageRect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
22.色值生成顏色
.h
@interface UIColor (HHCategory)
/**
- @brief 根據色值得到顏色
- @param hex 16進制的色值
**/
+(UIColor *)HH_ColorWithHex:(int)hex;
/**
- @brief 根據色值得到顏色
- @param hexString 16進制色值
**/
+(UIColor *)HH_ColorWithHexString:(NSString *)hexString;
/**
- @brief 根據色值得到顏色
- @param hexString 16進制色值
- @param alpha 透明值
**/
+(UIColor *)HH_ColorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;
@end
.m
import "UIColor+HHCategory.h"
@implementation UIColor (HHCategory)
pragma mark - 根據色值生成顏色
+(UIColor *)HH_ColorWithHex:(int)hex
{
return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0 green:((float)((hex & 0xFF00) >> 8))/255.0 blue:((float)(hex & 0xFF))/255.0 alpha:1.0];
}
pragma mark - 根據16進制色值字符串生成顏色
+(UIColor *)HH_ColorWithHexString:(NSString *)hexString
{
return [self HH_GetColorWithHexString:hexString alpha:1.0];
}
pragma mark - 根據16進制色值字符串和透明度生成顏色
+(UIColor *)HH_ColorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha
{
return [self HH_GetColorWithHexString:hexString alpha:alpha];
}
pragma mark - 根據16進制色值字符串和透明度生成顏色
-
(UIColor *)HH_GetColorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha
{
float red ,blue,green;
NSMutableString * colorString = [hexString mutableCopy];
if ([colorString hasPrefix:@"0x"]||[colorString hasPrefix:@"0X"]) {
[colorString replaceCharactersInRange:NSMakeRange(0, 2) withString:@""];
}if ([colorString hasPrefix:@"#"]) {
[colorString replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
}if ([colorString length]>=2) {
NSString * oneString = [hexString substringWithRange:NSMakeRange(0, 1)];
NSString * towString = [hexString substringWithRange:NSMakeRange(1, 1)];
red = [self hexString:oneString]*16+ [self hexString:towString];
}
else
{
red = 0;
}
if ([colorString length]>=4) {
NSString * oneString = [hexString substringWithRange:NSMakeRange(2, 1)];
NSString * towString = [hexString substringWithRange:NSMakeRange(3, 1)];
green = [self hexString:oneString]*16+ [self hexString:towString];
}
else
{
green = 0;
}
if ([colorString length]>=6) {
NSString * oneString = [hexString substringWithRange:NSMakeRange(4, 1)];
NSString * towString = [hexString substringWithRange:NSMakeRange(5, 1)];
blue = [self hexString:oneString]*16+ [self hexString:towString];
}
else
{
blue = 0;
}
return [UIColor colorWithRed:red/255 green:green/255 blue:blue/255 alpha:alpha];
}
pragma mark - 根據16進制色值字符串轉成數值
+(int)hexString:(NSString *)charString
{
if ([charString isEqualToString:@"0"]) {
return 0;
}
if ([charString isEqualToString:@"1"]) {
return 1;
}
if ([charString isEqualToString:@"2"]) {
return 2;
}
if ([charString isEqualToString:@"3"]) {
return 3;
}
if ([charString isEqualToString:@"4"]) {
return 4;
}
if ([charString isEqualToString:@"5"]) {
return 5;
}
if ([charString isEqualToString:@"6"]) {
return 6;
}
if ([charString isEqualToString:@"7"]) {
return 7;
}
if ([charString isEqualToString:@"8"]) {
return 8;
}
if ([charString isEqualToString:@"9"]) {
return 9;
}
if ([charString isEqualToString:@"a"] ||[charString isEqualToString:@"A"]) {
return 10;
}
if ([charString isEqualToString:@"b"]||[charString isEqualToString:@"B"]) {
return 11;
}
if ([charString isEqualToString:@"c"]||[charString isEqualToString:@"C"]) {
return 12;
}
if ([charString isEqualToString:@"d"]||[charString isEqualToString:@"D"]) {
return 13;
}
if ([charString isEqualToString:@"e"]||[charString isEqualToString:@"E"]) {
return 14;
}
if ([charString isEqualToString:@"f"]||[charString isEqualToString:@"F"]) {
return 15;
}
return 0;
}
@end
23.獲取app信息
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// 當前應用名稱
NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
if(appCurName == nil){
appCurName = [infoDictionary objectForKey:@"CFBundleName"];
}
NSLog(@"應用名稱:%@",appCurName);
// 版本 比如:1.0.1
NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
NSLog(@"版本:%@",appCurVersion);
UIDevice *device = [UIDevice currentDevice];
//手機別名
NSString* userPhoneName = [device name];
NSLog(@"手機別名: %@", userPhoneName);
//系統(tǒng)名稱
NSString* osName = [device systemName];
NSLog(@"設備名稱: %@",osName );
//手機系統(tǒng)版本
NSString* phoneVersion = [device systemVersion];
NSLog(@"手機系統(tǒng)版本: %@", phoneVersion);
//手機型號
NSString* phoneModel = [device model];
NSLog(@"手機型號: %@",phoneModel );
//地方型號 (國際化區(qū)域名稱)
NSString* localPhoneModel = [device localizedModel];
NSLog(@"國際化區(qū)域名稱: %@",localPhoneModel );