首先谢谢各位大神的分享,小兵在这里整理收集iOS 开发中各种小技巧,有喜欢的可以关注下;
感谢 判若两人丶
UITextField使用注意
先贴一个UITextField如何设置占位文字的颜色, 如果不先设置占位文字, 占位文字的颜色是不管用的:
//先设置占位文字
textField.placeholder = @"设置了占位文字内容以后, 才能设置占位文字的颜色";
//占位文字颜色
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
大家监听UITextField文字的改变会用到代理:
#pragma mark - <UITextFieldDelegate>
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//这里监听文字改变
return YES;
}
但是这个代理方法监听会有问题如下图:
2353624-366e3c826e58adaf.png 2353624-44c4588449a266b4.png所以我们要监听UITextField的文字改变不建议使用代理, 我们用addTarget监听文字
[textField addTarget:self action:@selector(textEditingChanged) forControlEvents:UIControlEventEditingChanged];
TableView拉伸头部图片、导航栏渐变效果
self.tableView.contentInset = UIEdgeInsetsMake(headH + tabBarH, 0, 0, 0);
self.automaticallyAdjustsScrollViewInsets = NO;
// 给导航条的背景图片传递一个空图片的UIImage对象
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
// 隐藏底部阴影条,传递一个空图片的UIImage对象
[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
//设置图片透明度
- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image {
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextSetAlpha(ctx, alpha);
CGContextDrawImage(ctx, area, image.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (UIImage *)imageWithColor:(UIColor *)color {
// 描述矩形
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
// 开启位图上下文
UIGraphicsBeginImageContext(rect.size);
// 获取位图上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 使用color演示填充上下文
CGContextSetFillColorWithColor(context, [color CGColor]);
// 渲染上下文
CGContextFillRect(context, rect);
// 从上下文中获取图片
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
// 结束上下文
UIGraphicsEndImageContext();
return theImage;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetY = scrollView.contentOffset.y;
CGFloat delta = offsetY - _lastOffsetY;
// 往上拖动,高度减少。
CGFloat height = headH - delta;
if (height < headMinH) {
height = headMinH;
}
_headHCons.constant = height;
// 设置导航条的背景图片
CGFloat alpha = delta / (headH - headMinH);
// 当alpha大于1,导航条半透明,因此做处理,大于1,就直接=0.99
if (alpha >= 1) {
alpha = 0.99;
}
_nameLabel.alpha = alpha;
// 设置导航条的背景图片
UIImage *image = [UIImage imageWithColor:[UIColor colorWithWhite:1 alpha:alpha]];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}
获取通讯录(联系人信息)
Unknown.png Unknown-1.png磁盘总空间大小
1、 获取磁盘总空间大小
//磁盘总空间
+ (CGFloat)diskOfAllSizeMBytes{
CGFloat size = 0.0;
NSError *error;
NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
#ifdef DEBUG
NSLog(@"error: %@", error.localizedDescription);
#endif
}else{
NSNumber *number = [dic objectForKey:NSFileSystemSize];
size = [number floatValue]/1024/1024;
}
return size;
}
2、 获取磁盘可用空间大小
//磁盘可用空间
+ (CGFloat)diskOfFreeSizeMBytes{
CGFloat size = 0.0;
NSError *error;
NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
#ifdef DEBUG
NSLog(@"error: %@", error.localizedDescription);
#endif
}else{
NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
size = [number floatValue]/1024/1024;
}
return size;
}
3、 获取指定路径下某个文件的大小
//获取文件大小
+ (long long)fileSizeAtPath:(NSString *)filePath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) return 0;
return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
}
4、获取文件夹下所有文件的大小
//获取文件夹下所有文件的大小
+ (long long)folderSizeAtPath:(NSString *)folderPath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
NSString *fileName;
long long folerSize = 0;
while ((fileName = [filesEnumerator nextObject]) != nil) {
NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
folerSize += [self fileSizeAtPath:filePath];
}
return folerSize;
}
NSString处理
1、 获取字符串(或汉字)首字母
//获取字符串(或汉字)首字母
+ (NSString *)firstCharacterWithString:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringToIndex:1];
}
2、将字符串数组按照元素首字母顺序进行排序分组
//将字符串数组按照元素首字母顺序进行排序分组
-(NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
if (array.count == 0) {
return nil;
}
for (id obj in array) {
if (![obj isKindOfClass:[NSString class]]) {
return nil;
}
}
UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
//创建27个分组数组
for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
NSMutableArray *obj = [NSMutableArray array];
[objects addObject:obj];
}
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
//按字母顺序进行分组
NSInteger lastIndex = -1;
for (int i = 0; i < array.count; i++) {
NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
[[objects objectAtIndex:index] addObject:array[i]];
lastIndex = index;
}
//去掉空数组
for (int i = 0; i < objects.count; i++) {
NSMutableArray *obj = objects[i];
if (obj.count == 0) {
[objects removeObject:obj];
}
}
//获取索引字母
for (NSMutableArray *obj in objects) {
NSString *str = obj[0];
NSString *key = [self firstCharacterWithString:str];
[keys addObject:key];
}
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:objects forKey:keys];
return dic;
}
//获取字符串(或汉字)首字母
- (NSString *)firstCharacterWithString:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringToIndex:1];
}
NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];
NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];
NSLog(@"\n\ndic: %@", dic);
输出结果如下:
Unknown-2.pngUIImage 相关处理
1、对图片进行滤镜处理
#pragma mark - 对图片进行滤镜处理
// 怀旧 --> CIPhotoEffectInstant 单色 --> CIPhotoEffectMono
// 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade
// 色调 --> CIPhotoEffectTonal 冲印 --> CIPhotoEffectProcess
// 岁月 --> CIPhotoEffectTransfer 铬黄 --> CIPhotoEffectChrome
// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField
+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter = [CIFilter filterWithName:name];
[filter setValue:inputImage forKey:kCIInputImageKey];
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return resultImage;
}
2、 调整图片饱和度、亮度、对比度
/**
* 调整图片饱和度, 亮度, 对比度
*
* @param image 目标图片
* @param saturation 饱和度
* @param brightness 亮度: -1.0 ~ 1.0
* @param contrast 对比度
*
*/- (UIImage *)colorControlsWithOriginalImage:(UIImage *)image
saturation:(CGFloat)saturation
brightness:(CGFloat)brightness
contrast:(CGFloat)contrast{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
[filter setValue:inputImage forKey:kCIInputImageKey];
[filter setValue:@(saturation) forKey:@"inputSaturation"];
[filter setValue:@(brightness) forKey:@"inputBrightness"];
[filter setValue:@(contrast) forKey:@"inputContrast"];
CIImage *result = [filter valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return resultImage;
}
3、 全屏截图
//全屏截图
+ (UIImage *)shotScreen{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIGraphicsBeginImageContext(window.bounds.size);
[window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
4、 截取一张 view 生成图片
//截取view生成一张图片
+ (UIImage *)shotWithView:(UIView *)view{
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
5、 截取view中某个区域生成一张图片
//截取view中某个区域生成一张图片
+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
UIGraphicsBeginImageContext(scope.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
CGContextTranslateCTM(context, 0, rect.size.height);//下移
CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
CGContextDrawImage(context, rect, imageRef);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(imageRef);
CGContextRelease(context);
return image;
}
6、判断是否为gif/png图片的正确姿势
//假设这是一个网络获取的URL
NSString *path = @"http://pic3.nipic.com/20090709/2893198_075124038_2.gif";
// 判断是否为gif
NSString *extensionName = path.pathExtension;
if ([extensionName.lowercaseString isEqualToString:@"gif"]) {
//是gif图片
} else {
//不是gif图片
}
什么难道你不是这么判断的么 ? 哦~ 我懂了, 难道你使用字符串截取来判断的吗 ? 哈哈开个玩笑!
以上判断看似是可以的,但是这不严谨的, 在不知道图片扩展名的情况下, 如何知道图片的真实类型 ? 其实就是取出图片数据的第一个字节, 就可以判断出图片的真实类型那该怎么做呢如下:
//通过图片Data数据第一个字节 来获取图片扩展名
- (NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"jpeg";
case 0x89:
return @"png";
case 0x47:
return @"gif";
case 0x49:
case 0x4D:
return @"tiff";
case 0x52:
if ([data length] < 12) {
return nil;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
return @"webp";
}
return nil;
}
return nil;
}
7、设置图片圆角?
//cornerRadius 设置为self.iconImage图片宽度的一半(圆形图片)
self.iconImage.layer.cornerRadius = 20;
self.iconImage.layer.masksToBounds = YES;
在此之后建议大家尽量不要这么设置, 因为使用图层过量会有卡顿现象, 特别是弄圆角或者阴影会很卡, 如果设置图片圆角我们一般用绘图来做:
/** 设置圆形图片(放到分类中使用) */
- (UIImage *)cutCircleImage {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 获取上下文
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 设置圆形
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctr, rect);
// 裁剪
CGContextClip(ctr);
// 将图片画上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
UILabel修改行距,首行缩进
1.UILabel修改文字行距,首行缩进
lineSpacing: 行间距
firstLineHeadIndent:首行缩进
font: 字体
textColor: 字体颜色
- (NSDictionary *)settingAttributesWithLineSpacing:(CGFloat)lineSpacing FirstLineHeadIndent:(CGFloat)firstLineHeadIndent Font:(UIFont *)font TextColor:(UIColor *)textColor{
//分段样式
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//行间距
paragraphStyle.lineSpacing = lineSpacing;
//首行缩进
paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;
//富文本样式
NSDictionary *attributeDic = @{
NSFontAttributeName : font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName : textColor
};
return attributeDic;
}
网友评论