iOS小技巧3

时间:2024-07-26 15:38:08
将颜色合成图片

将颜色合成图片
+(UIImage *)imageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
navigationController 设置title 颜色

    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], UITextAttributeTextColor,
nil, UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(, )], UITextAttributeTextShadowOffset,
[UIFont fontWithName:@"Arial-Bold" size:0.0], UITextAttributeFont,
nil]];
设置全局navigation barbuttonitem 

#pragma mark 设置全局navigation barbuttonitem
-(void)setNaviBarButtonItemImage:(NSString *)imageName andX:(NSInteger)x andY:(NSInteger)y andW:(NSInteger)w andH:(NSInteger)h andTitle:(NSString *)title andSel:(SEL)sel andLOrR:(NSString *)lOr andTitleColor:(UIColor *)color{ UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame =CGRectMake(x,y,w,h); [btn setTitle:title forState:UIControlStateNormal]; if (imageName.length== && title.length==) { } else if (imageName.length== && title.length!=) {
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTitleColor:color forState:UIControlStateNormal];
}else if(imageName.length!= && title.length==){
UIImage *image = [UIImage imageNamed:imageName];
[btn setImage:image forState:UIControlStateNormal];
}else if(imageName.length!= && title.length!=){
UIImage *image = [UIImage imageNamed:imageName];
[btn setBackgroundImage:image forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setTitleColor:color forState:UIControlStateNormal];
} [btn addTarget: self action:sel forControlEvents: UIControlEventTouchUpInside];
UIBarButtonItem *bBtn = [[UIBarButtonItem alloc]initWithCustomView:btn]; if ([lOr isEqualToString:@"left"]) {
[self.navigationItem setLeftBarButtonItem:bBtn];
}else{
[self.navigationItem setRightBarButtonItem:bBtn];
}
}
设置导航条标题的颜色

[navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
计算文字的Size

/**

 *  计算文字尺寸

 *  @param text    需要计算尺寸的文字

 *  @param font    文字的字体

 *  @param maxSize 文字的最大尺寸

 */

- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize

{

    NSDictionary *attrs = @{NSFontAttributeName : font};

    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;

}
两种方法删除NSUserDefaults所有记录

//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; //方法二
- (void)resetDefaults {
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
}
设置Label行间距

设置label的行间距,计算高度
-(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndLineSpacing:(float)lineSpacing
{
//富文本设置文字行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineSpacing = lineSpacing; NSDictionary *attributes = @{ NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle};
labell.attributedText = [[NSAttributedString alloc]initWithString:labell.text attributes:attributes];
} //获取设置文本间距以后的高度
CGRect huiDaSize = [cell.fabiaoHuifuContentLabel.attributedText boundingRectWithSize:CGSizeMake(, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
一行代码创建AlertView,支持多个参数

一行代码创建AlertView,支持多个参数
//
// UIAlertView+Additions.h
//
//
// Created by Jueying on 15/1/15.
// Copyright (c) 2015年 Jueying. All rights reserved.
// #import <UIKit/UIKit.h> typedef void(^UIAlertViewCallBackBlock)(NSInteger buttonIndex); @interface UIAlertView (Additions) <UIAlertViewDelegate> @property (nonatomic, copy) UIAlertViewCallBackBlock alertViewCallBackBlock; + (void)alertWithCallBackBlock:(UIAlertViewCallBackBlock)alertViewCallBackBlock title:(NSString *)title message:(NSString *)message cancelButtonName:(NSString *)cancelButtonName otherButtonTitles:(NSString *)otherButtonTitles, ...; @end //
// UIAlertView+Additions.m
//
//
// Created by Jueying on 15/1/15.
// Copyright (c) 2015年 Jueying. All rights reserved.
// #import "UIAlertView+Additions.h"
#import <objc/runtime.h> static void* UIAlertViewKey = @"UIAlertViewKey"; @implementation UIAlertView (Additions) + (void)alertWithCallBackBlock:(UIAlertViewCallBackBlock)alertViewCallBackBlock title:(NSString *)title message:(NSString *)message cancelButtonName:(NSString *)cancelButtonName otherButtonTitles:(NSString *)otherButtonTitles, ... { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:cancelButtonName otherButtonTitles: otherButtonTitles, nil];
NSString *other = nil;
va_list args;
if (otherButtonTitles) {
va_start(args, otherButtonTitles);
while ((other = va_arg(args, NSString*))) {
[alert addButtonWithTitle:other];
}
va_end(args);
}
alert.delegate = alert;
[alert show];
alert.alertViewCallBackBlock = alertViewCallBackBlock;
} - (void)setAlertViewCallBackBlock:(UIAlertViewCallBackBlock)alertViewCallBackBlock { [self willChangeValueForKey:@"callbackBlock"];
objc_setAssociatedObject(self, &UIAlertViewKey;, alertViewCallBackBlock, OBJC_ASSOCIATION_COPY);
[self didChangeValueForKey:@"callbackBlock"];
} - (UIAlertViewCallBackBlock)alertViewCallBackBlock { return objc_getAssociatedObject(self, &UIAlertViewKey;);
} - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (self.alertViewCallBackBlock) {
self.alertViewCallBackBlock(buttonIndex);
}
} @end
一段文字设置多种字体颜色

给定range和需要设置的颜色,就可以给一段文字设置多种不同的字体颜色,使用方法如下:
[self fuwenbenLabel:contentLabel FontNumber:[UIFont systemFontOfSize:] AndRange:NSMakeRange(, ) AndColor:RGBACOLOR(, , , )];
//设置不同字体颜色
-(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text]; //设置字号
[str addAttribute:NSFontAttributeName value:font range:range]; //设置文字颜色
[str addAttribute:NSForegroundColorAttributeName value:vaColor range:range]; labell.attributedText = str;
}
隐藏状态栏

-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] setStatusBarHidden:NO]; }
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
}
ScaleTableView-头部图片可伸缩的TableView

很多社交App中都有这样的设计。 列表顶部是一张大图,大图可以随着列表的下拉而放大。本Demo实现了这个功能。
//
// ViewController.m
// ScaleTableView
//
// Created by ShawnPan on 15/3/25.
// Mail : developerpans@163.com
// Copyright (c) 2015年 ShawnPan. All rights reserved.
// #import "ViewController.h"
#define Imgwidth 828
#define Imgheight 589
#define ScaleImageViewHeight ([UIScreen mainScreen].bounds.size.width*Imgheight/Imgwidth)
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *scaleImageView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIImageView *noScaleImage;
@property (strong, nonatomic) IBOutlet UILabel *nicknameLabel; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.dataSource = self; }
- (void)viewWillAppear:(BOOL)animated
{
self.tableView.contentInset = UIEdgeInsetsMake(ScaleImageViewHeight, , , );
self.scaleImageView.frame = CGRectMake(, -ScaleImageViewHeight, self.view.frame.size.width, ScaleImageViewHeight);
[self.tableView addSubview:self.scaleImageView];
self.noScaleImage.frame = CGRectMake(, -, , );
[self.tableView addSubview:self.noScaleImage];
self.nicknameLabel.frame = CGRectMake(, -, , );
[self.tableView addSubview:self.nicknameLabel];
} #pragma - mark UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat y = scrollView.contentOffset.y;
if (y < -ScaleImageViewHeight)
{
CGRect frame = self.scaleImageView.frame;
frame.size.height = -y;
frame.origin.y = y;
self.scaleImageView.frame = frame;
}
} #pragma - mark UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return ;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
cell.textLabel.text = [@(indexPath.row) stringValue];
return cell;
}
@end
//将状态栏文字颜色变成黑色
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (is_IOS_7) {//更改时间颜色
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}
} -(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated]; if (is_IOS_7) {//更改时间颜色
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}
}
在tabbar上添加小红点

在tabbar上添加类似于badgevalue功能的小红点。
只需要知道tabbar的下标
使用- (void)showBadgeOnItemIndex:(int)index
和 - (void)hideBadgeOnItemIndex:(int)index进行显示和隐藏
使用方法如下:[self.tabBarController.tabBar showBadgeOnItemIndex:];
#import "UITabBar+badge.h" #define TabbarItemNums 4.0 //tabbar的数量 @implementation UITabBar (badge) - (void)showBadgeOnItemIndex:(int)index{ [self removeBadgeOnItemIndex:index]; UIView *badgeView = [[UIView alloc]init]; badgeView.tag = + index; badgeView.layer.cornerRadius = ; badgeView.backgroundColor = [UIColor redColor]; CGRect tabFrame = self.frame; float percentX = (index +0.6) / TabbarItemNums; CGFloat x = ceilf(percentX * tabFrame.size.width); CGFloat y = ceilf(0.1 * tabFrame.size.height); badgeView.frame = CGRectMake(x, y, , ); [self addSubview:badgeView]; } - (void)hideBadgeOnItemIndex:(int)index{ [self removeBadgeOnItemIndex:index]; } - (void)removeBadgeOnItemIndex:(int)index{ for (UIView *subView in self.subviews) { if (subView.tag == +index) { [subView removeFromSuperview]; }
}
} @end
获取一个类的所有子类

通过objc_copyClassList获取所有类,并通过class_getSuperclass来判断那类型继承于该类
+ (NSArray *) allSubclasses
{
Class myClass = [self class];
NSMutableArray *mySubclasses = [NSMutableArray array]; unsigned int numOfClasses;
Class *classes = objc_copyClassList(&numOfClasses;);
for (unsigned int ci = ; ci < numOfClasses; ci++) {
Class superClass = classes[ci];
do {
superClass = class_getSuperclass(superClass);
} while (superClass && superClass != myClass); if (superClass)
[mySubclasses addObject: classes[ci]];
}
free(classes); return mySubclasses;
}
类似广告的文字循环滚动

-(void)viewDidLoad
{
timer = [[NSTimer alloc] init]; mainsco = [[UIScrollView alloc] initWithFrame:CGRectMake(, , , )];
mainsco.backgroundColor = [UIColor clearColor];
[bgView addSubview:mainsco];
//显示广告内容
noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
noticeLabel.numberOfLines = ;
noticeLabel.font = [UIFont systemFontOfSize:13.0f];
noticeLabel.backgroundColor = [UIColor clearColor];
[mainsco addSubview:noticeLabel]; noticeLabel.text =[dic valueForKey:@"Bulletin"]; noticeSize = [ [dic valueForKey:@"Bulletin"] sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(, )];
//所有文字显示在一行所占的高度
size1 = [[dic valueForKey:@"Bulletin"] sizeWithFont:[UIFont systemFontOfSize:13.0f]];
mainsco.contentSize = CGSizeMake(, noticeSize.height);
mainsco.showsVerticalScrollIndicator = NO;
//根据文字的多少设置label的宽高,但底层的scrollview只显示一行内容的高度
noticeLabel.frame = CGRectMake(, , , noticeSize.height); mainsco.frame =CGRectMake(, , , size1.height);
if (noticeSize.height>size1.height)
{
//如果文字大于一行就开始滚动,否则停止timer
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(time) userInfo:self repeats:YES]; }else{
[timer invalidate];
}

//滚动的方法
-(void)time
{
//oldy用来记录上一次scrollview滚动的位置
mainsco.contentOffset = CGPointMake(, oldy);
if (oldy>noticeSize.height-) {
oldy = ;
}else
oldy++;//设置每次滚动的高度,即几个像素
}
分组列表头部空白处理

在viewWillAppear里面添加如下代码:
//分组列表头部空白处理
CGRect frame = myTableView.tableHeaderView.frame;
frame.size.height = 0.1;
UIView *headerView = [[UIView alloc] initWithFrame:frame];
[myTableView setTableHeaderView:headerView];
阿拉伯数字转化为汉语数字
+(NSString *)translation:(NSString *)arebic { NSString *str = arebic;
NSArray *arabic_numerals = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];
NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals]; NSMutableArray *sums = [NSMutableArray array];
for (int i = ; i < str.length; i ++) {
NSString *substr = [str substringWithRange:NSMakeRange(i, )];
NSString *a = [dictionary objectForKey:substr];
NSString *b = digits[str.length -i-];
NSString *sum = [a stringByAppendingString:b];
if ([a isEqualToString:chinese_numerals[]])
{
if([b isEqualToString:digits[]] || [b isEqualToString:digits[]])
{
sum = b;
if ([[sums lastObject] isEqualToString:chinese_numerals[]])
{
[sums removeLastObject];
}
}else
{
sum = chinese_numerals[];
} if ([[sums lastObject] isEqualToString:sum])
{
continue;
}
} [sums addObject:sum];
} NSString *sumStr = [sums componentsJoinedByString:@""];
NSString *chinese = [sumStr substringToIndex:sumStr.length-];
NSLog(@"%@",str);
NSLog(@"%@",chinese);
return chinese;
}
切割字符串工具。。

字符串~`!@#$%^&*()_-+={}[]|\\:;\"'<,>.?/ 打印结果为 @"~",@"`",@"!",@"@",@"#",@"$",@"%",@"^",@"&",@"*",@"(",@")",@"_",@"-",@"+",@"=",@"{",@"}",@"[",@"]",@"|",@"\",@":",@";",@""",@"'",@"<",@",",@">",@".",@"?",@"/"
// QWERTYUIOPASDFGHJKLZXCVBNM
NSMutableString *str = [NSMutableString stringWithString:@"~`!@#$%^&*()_-+={}[]|\\:;\"'<,>.?/"];
NSMutableString *dest = [NSMutableString string];
for (int i = ; i < str.length; i++) {
NSMutableString *head = [NSMutableString stringWithString:@"@\""];
NSString *temp = [str substringWithRange:NSMakeRange(i, 1)];
[head appendFormat:@"%@\"",temp]; [dest appendFormat:@"%@,",head];
NSLog(@"%d", i);
}
NSLog(@"%@", dest);
仿iOS图标抖动

#import "LHViewController.h"
#define angelToRandian(x) ((x)/180.0*M_PI)
@interface LHViewController ()
@property (strong, nonatomic) IBOutlet UIImageView *imageView; @end @implementation LHViewController - (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UILongPressGestureRecognizer* longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
[self.imageView addGestureRecognizer:longPress];
} -(void)longPress:(UILongPressGestureRecognizer*)longPress
{
if (longPress.state==UIGestureRecognizerStateBegan) {
CAKeyframeAnimation* anim=[CAKeyframeAnimation animation];
anim.keyPath=@"transform.rotation";
anim.values=@[@(angelToRandian(-)),@(angelToRandian()),@(angelToRandian(-))];
anim.repeatCount=MAXFLOAT;
anim.duration=0.2;
[self.imageView.layer addAnimation:anim forKey:nil];
self.btn.hidden=NO;
}
} - (IBAction)delete:(id)sender {
[self.imageView removeFromSuperview];
[self.btn removeFromSuperview];
}
@end
//修改webView背景色
webView.backgroundColor = [UIColor clearColor];
[webView setOpaque:NO];
//自定义cell实际大小获取
- (void)awakeFromNib {
// Initialization code } -(void)drawRect:(CGRect)rect {
// 重写此方法,并在此方法中获取
CGFloat width = self.frame.size.width;
}
//获取网络图片的宽度
headerImageView.contentMode = UIViewContentModeScaleAspectFit;
[headerScrollView addSubview:headerImageView]; int imgWidth = headerImageView.image.size.width;
int imgHight = headerImageView.image.size.height; int aWidth = headerImageView.image.size.width/headerImageView.frame.size.width; int LastWidth = imgWidth/aWidth;
int LastHight = imgHight/aWidth; //视频暂停图片
UIImageView *imageee = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-)/, (SCREEN_HEIGHT-)/, /, /)];
imageee.image = LOAD_IMAGE(@"newhouse_mov_stop");
imageee.center = headerImageView.center;
[headerScrollView addSubview:imageee]; UIButton *movbtn = [[UIButton alloc] initWithFrame:CGRectMake(+i*SCREEN_WIDTH, , LastWidth, LastHight)];
movbtn.backgroundColor = [UIColor clearColor];
movbtn.tag = +i;
[movbtn addTarget:self action:@selector(doBoFang:) forControlEvents:UIControlEventTouchUpInside];
movbtn.center = headerImageView.center;
[headerScrollView addSubview:movbtn];
//获取当前屏幕显示的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:];
id nextResponder = [frontView nextResponder]; if ([nextResponder isKindOfClass:[UIViewController class]])
result = nextResponder;
else
result = window.rootViewController; return result;
}
UILABLE自适应

CGRect rect = [operation boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:],NSFontAttributeName,nil] context:nil];
Xcode编译错误集锦
、在将ios项目进行Archive打包时,Xcode提示以下错误:
[BEROR]CodeSign error: Certificate identity ‘iPhone Distribution: ***.’ appears more than once in the keychain. The codesign tool requires there only be one.
原因:那么出现此问题的原因是多个证书之间冲突造成两种解决方法如下:
解决办法:打开mac系统的“实用工具”-“钥匙串访问”-“我的证书”中,会看到有证书名一模一样的,那么请将早期的证书删除掉,重启Xcode; 、在真机或者模拟器编译程序的时候可能会遇到下面的错误:
Could not change executable permissions on the application.
原因:拥有相同的bundle Identifier已经在设备上运行
解决办法:删除设备中或者模拟器中的App。 、编译时遇到如下错误:
A valid provisioning profile matching the application's Identifier 'XXXX' could not be found
原因:缺少证书或者是在Code Signing Identity处没有选择对应的证书或者是证书不对应
解决办法:重装证书,检查证书是否是否选择是否对应。 、编译时遇到如下错误:
ld: library not found for -lmp3lameclang: error: linker command failed with exit code (use -v to see invocation)
原因:一般是多人编辑同一个工程时其中一人没将某个库上传导致的
解决办法:上传具体静态库
//导航栏色调

self.navigationBar.barTintColor = [UIColor colorWithRed:0.01 green:0.05 blue:0.06 alpha:]; //%%% bartint
self.navigationBar.translucent = NO;
viewControllerArray = [[NSMutableArray alloc]init];
currentPageIndex = ; //设置状态栏颜色 -(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent; // return UIStatusBarStyleDefault;
}