原创:知识点总结性文章
创作不易,请珍惜,之后会持续更新,不断完善
个人比较喜欢做笔记和写总结,毕竟好记性不如烂笔头哈哈,这些文章记录了我的IOS成长历程,希望能与大家一起进步
温馨提示:由于简书不支持目录跳转,大家可通过command + F 输入目录标题后迅速寻找到你所需要的内容
目录
- 一、UILabel
- 改变行、字间距
- 字体高亮显示
- 调整文本显示优先级
- 二、NSString
- 判断一个字符串是否都是纯数字
- 计算字符串长度(一行时候)
- 根据字体、行数、行间距和constrainedWidth计算文本占据的size
- 安全截取字符串
- 校验字符是否金额
- 三、UIImage
- 绘制圆角
- 通过颜色来生成图片
- 四、UIScreen
- 获取UIScreen的属性值
- 五、UIView
- 获取UIView的属性值
- 六、UIColor
- 使用16进制进行颜色设置
- 随机颜色
- 七、UINavigationController
- 弹出到指定的页面类
- 移除指定的页面类
- 得到需要移除的View
- 八、UIButton
- 设置按钮响应区域
- 九、UITableView
- 滚动到顶部
- 十、UIPasteboard
- 设置剪贴板
- 获取剪贴板
- Pod库
- Demo
- 参考文献
一、UILabel
改变行、字间距
a、运行效果

b、功能代码
/** 改变行、字间距 */
- (void)changeLabelWithLineSpace:(float)lineSpace WordSpace:(float)wordSpace;
// 改变行、字间距
- (void)changeLabelWithLineSpace:(float)lineSpace WordSpace:(float)wordSpace
{
NSString *labelText = self.text;
// 改变字间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(wordSpace)}];
// 改变行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpace];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
self.attributedText = attributedString;
[self sizeToFit];
}
字体高亮显示
a、运行效果

b、功能代码
- (void)setHighlightfullString:(NSString *)fullString lightString:(NSString *)lightString lightColor:(UIColor *)color lightFont:(UIFont *)font
{
if (fullString == nil || [fullString isEqualToString:@""])
{
return;
}
NSMutableAttributedString *mutableAttributedStr = [[NSMutableAttributedString alloc] initWithString:fullString];
if (lightString == nil || [lightString isEqualToString:@""])
{
[self setAttributedText:mutableAttributedStr];
}
NSRange range = [[fullString uppercaseString] rangeOfString:[lightString uppercaseString]];
if (color == nil)
{
color = [UIColor redColor];
}
if (font)
{
[mutableAttributedStr addAttribute:NSFontAttributeName value:font range:range];
}
[mutableAttributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
[self setAttributedText:mutableAttributedStr];
}
调整文本显示优先级
当特长的时候降低一下优先级
- (void)lowPriority
{
[self setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
[self setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
}
当特长的时候固定,不被拉伸也不被压缩
- (void)highPriority
{
[self setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
[self setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
}
二、NSString
判断一个字符串是否都是纯数字
a、运行效果
2020-09-28 10:49:11.712148+0800 FunctionCodeBlockDemo[26982:19380368] 待校验的字符串为:谢佳培
2020-09-28 10:49:11.712483+0800 FunctionCodeBlockDemo[26982:19380368] 格式错误
2020-09-28 10:49:26.339029+0800 FunctionCodeBlockDemo[26997:19382035] 待校验的字符串为:123456
2020-09-28 10:49:26.342230+0800 FunctionCodeBlockDemo[26997:19382035] 格式正确
b、功能代码
/** 判断一个字符串是否都是纯数字 */
- (BOOL)judgeIsPureInt;
// 判断一个字符串是否都是纯数字
- (BOOL)judgeIsPureInt
{
NSScanner *scan = [NSScanner scannerWithString:self];
int value;
return [scan scanInt:&value] && [scan isAtEnd];
}
计算字符串长度(一行时候)
a、运行效果

2020-11-03 15:35:13.756807+0800 CategoryDemo[924:4225045] 计算字符串长度(一行时候),宽度:312.000000,高度:22.000000
b、功能代码
- (CGSize)textSizeWithFont:(UIFont*)font limitWidth:(CGFloat)maxWidth
{
CGSize size = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, 36)options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{ NSFontAttributeName : font} context:nil].size;
size.width = size.width > maxWidth ? maxWidth : size.width;
size.width = ceil(size.width);
size.height = ceil(size.height);
return size;
}
c、调用方式
- (void)testLimitTextWidth
{
NSString *limitText = @"他还没有学会阅读便在头脑里构思故事";
CGSize limitWidth = [limitText textSizeWithFont:[UIFont systemFontOfSize:18] limitWidth:400];
NSLog(@"计算字符串长度(一行时候),宽度:%f,高度:%f",limitWidth.width,limitWidth.height);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 300, limitWidth.width, limitWidth.height)];
label.text = limitText;
label.backgroundColor = [UIColor yellowColor];
[self.view addSubview:label];
}
根据字体、行数、行间距和constrainedWidth计算文本占据的size
a、运行效果

2020-11-03 15:38:54.847997+0800 CategoryDemo[978:4228285] 根据字体、行数、行间距和constrainedWidth计算文本占据的size,宽度:300.000000,高度:241.285156
b、功能代码
- (CGSize)textSizeWithFont:(UIFont*)font
numberOfLines:(NSInteger)numberOfLines
lineSpacing:(CGFloat)lineSpacing
constrainedWidth:(CGFloat)constrainedWidth
{
if (self.length == 0)
{
return CGSizeZero;
}
CGFloat oneLineHeight = font.lineHeight;
CGSize textSize = [self boundingRectWithSize:CGSizeMake(constrainedWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
// 行数
CGFloat rows = textSize.height / oneLineHeight;
CGFloat realHeight = oneLineHeight;
if (numberOfLines == 0)// 0表示不限制行数,需要真实高度加上行间距
{
if (rows >= 1)
{
realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
}
}
else// 行数超过指定行数的时候,限制行数
{
if (rows > numberOfLines)
{
rows = numberOfLines;
}
realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
}
// 返回真实的宽高
return CGSizeMake(constrainedWidth, realHeight);
}
c、调用方式
- (void)textSizeWithFont
{
NSString *text = @"老伯爵看到列文的好,是站在一个成熟男人角度,看出列文有实干,成熟,不做作,理智的许多优点,他实诚,不虚伪,真实。而大多数他眼中的青年都是在一个模子里刻出来那种,旧的上流社会沾染了的虚伪,狡诈,奉承的习气,相比之下,列文在他心中才是真是,优秀,能够給女儿真正幸福生活的人选。很可惜,安娜就没有这样好的父亲给她在人生最初把关。";
CGSize size = [text textSizeWithFont:[UIFont systemFontOfSize:18] numberOfLines:0 lineSpacing:0.5 constrainedWidth:300];
NSLog(@"根据字体、行数、行间距和constrainedWidth计算文本占据的size,宽度:%f,高度:%f",size.width,size.height);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 300, 300, size.height)];
label.text = text;
label.numberOfLines = 0;
label.backgroundColor = [UIColor yellowColor];
[self.view addSubview:label];
}
安全截取字符串
a、运行效果
2020-11-03 15:59:33.829751+0800 CategoryDemo[1410:4243203] ToIndex超范围了:,FromIndex超范围了:
2020-11-03 15:59:33.829852+0800 CategoryDemo[1410:4243203] 删除第一个字符:ieJia,删除最后一个字符:XieJi
b、功能代码
从字符串的起始处提取到某个位置结束
- (NSString *)substringToIndexSafe:(NSUInteger)to
{
if (self == nil || [self isEqualToString:@""])
{
return @"";
}
if (to > self.length - 1)
{
return @"";
}
return [self substringToIndex:to];
}
从字符串的某个位置开始提取直到字符串的末尾
- (NSString *)substringFromIndexSafe:(NSInteger)from
{
if (self == nil || [self isEqualToString:@""])
{
return @"";
}
if (from > self.length - 1)
{
return @"";
}
return [self substringFromIndex:from];
}
删除字符串中的首字符
- (NSString *)deleteFirstCharacter
{
return [self substringFromIndexSafe:1];
}
删除字符串中的末尾字符
- (NSString *)deleteLastCharacter
{
return [self substringToIndexSafe:self.length - 1];
}
c、调用方式
- (void)testSafeSubstring
{
NSString *text = @"XieJia";
NSString *subToString = [text substringToIndexSafe:9];
NSString *subFromString = [text substringFromIndexSafe:9];
NSLog(@"ToIndex超范围了:%@,FromIndex超范围了:%@",subToString,subFromString);
NSString *deleteFirstCharacter = [text deleteFirstCharacter];
NSString *deleteLastCharacter = [text deleteLastCharacter];
NSLog(@"删除第一个字符:%@,删除最后一个字符:%@",deleteFirstCharacter,deleteLastCharacter);
}
正则表达式校验
校验字符是否金额
- (BOOL)checkPrice:(NSUInteger)integerLength decimalLenth:(NSUInteger)decimalLenth
{
NSString *regex = [NSString stringWithFormat:@"^\\d{1,%ld}(\\.\\d{0,%ld})?$", integerLength, decimalLenth];
return [self evaluateWithRegexString:regex];
}
校验是否纯数字
- (BOOL)checkIsNumber
{
NSString *regex = @"^[0-9]*$";
return [self evaluateWithRegexString:regex];
}
校验是否仅包含数字和大小写字母
- (BOOL)checkIsLettersAndNumbers
{
NSString *regex = @"^[A-Za-z0-9]+$";
return [self evaluateWithRegexString:regex];
}
三、UIImage
绘制圆角
a、运行效果

b、功能代码
// 弄圆角或者阴影会很卡,用绘图来做,放到分类中使用
- (UIImage *)cutCircleImage:(CGSize)size
{
UIGraphicsBeginImageContextWithOptions(size, NO, 1.0);
// 获取上下文
CGContextRef contextRef = UIGraphicsGetCurrentContext();
// 设置圆形
CGRect rect = CGRectMake(0, 0, size.width, size.height);
CGContextAddEllipseInRect(contextRef, rect);
// 裁剪
CGContextClip(contextRef);
// 将图片画上去
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
通过颜色来生成图片
a、运行效果

b、功能代码
+ (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;
}
c、调用方式
- (void)createImageByColor
{
UIImage *backImage = [UIImage imageWithColor:[UIColor blueColor]];
[self.navigationController.navigationBar setBackgroundImage:backImage forBarMetrics:UIBarMetricsDefault];
}
四、UIScreen
获取UIScreen的属性值
a、运行效果
2020-11-03 16:12:43.897164+0800 CategoryDemo[1770:4254266] 屏幕尺寸的宽:414.000000,高:896.000000,缩放率:3.000000
b、功能代码
// 尺寸
+ (CGSize)size
{
return [[UIScreen mainScreen] bounds].size;
}
// 宽度
+ (CGFloat)width
{
return [[UIScreen mainScreen] bounds].size.width;
}
// 高度
+ (CGFloat)height
{
return [[UIScreen mainScreen] bounds].size.height;
}
// 缩放率
+ (CGFloat)scale
{
return [UIScreen mainScreen].scale;
}
c、调用方式
2020-11-03 16:12:43.897164+0800 CategoryDemo[1770:4254266] 屏幕尺寸的宽:414.000000,高:896.000000,缩放率:3.000000
五、UIView
获取UIView的属性值
a、运行效果
2020-11-03 16:36:21.322922+0800 CategoryDemo[2291:4273987] Label的X坐标:100.000000,Y坐标:300.000000
2020-11-03 16:36:21.323024+0800 CategoryDemo[2291:4273987] Label的宽:200.000000,高:50.000000
2020-11-03 16:36:21.323103+0800 CategoryDemo[2291:4273987] Label的右边坐标:300.000000,底部坐标:350.000000
2020-11-03 16:36:21.323176+0800 CategoryDemo[2291:4273987] Label的中心点X坐标:200.000000,中心点Y坐标:325.000000
2020-11-03 16:36:21.323246+0800 CategoryDemo[2291:4273987] Label的起始点X坐标:100.000000,起始点Y坐标:300.000000
b、功能代码
X和Y坐标
- (CGFloat)x
{
return self.frame.origin.x;
}
- (void)setX:(CGFloat)x
{
self.frame = CGRectMake(x, self.y, self.width, self.height);
}
- (CGFloat)y
{
return self.frame.origin.y;
}
- (void)setY:(CGFloat)y
{
self.frame = CGRectMake(self.x, y, self.width, self.height);
}
宽度和高度
- (CGFloat)width
{
return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width
{
self.frame = CGRectMake(self.x, self.y, width, self.height);
}
- (CGFloat)height
{
return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height
{
self.frame = CGRectMake(self.x, self.y, self.width, 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;
}
- (CGFloat)bottom
{
return self.frame.origin.y + self.frame.size.height;
}
- (void)setBottom:(CGFloat)bottom
{
CGRect frame = self.frame;
frame.origin.y = bottom - frame.size.height;
self.frame = frame;
}
中心点
- (CGFloat)centerX
{
return self.center.x;
}
- (void)setCenterX:(CGFloat)centerX
{
self.center = CGPointMake(centerX, self.center.y);
}
- (CGFloat)centerY
{
return self.center.y;
}
- (void)setCenterY:(CGFloat)centerY
{
self.center = CGPointMake(self.center.x, centerY);
}
起始点
- (CGPoint)origin
{
return self.frame.origin;
}
- (void)setOrigin:(CGPoint)origin
{
CGRect frame = self.frame;
frame.origin = origin;
self.frame = frame;
}
尺寸大小
- (CGSize)size
{
return self.frame.size;
}
- (void)setSize:(CGSize)size
{
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
c、调用方式
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 300, 200, 50)];
label.backgroundColor = [UIColor yellowColor];
[self.view addSubview:label];
NSLog(@"Label的X坐标:%f,Y坐标:%f",[label x],[label y]);
NSLog(@"Label的宽:%f,高:%f",[label width],[label height]);
NSLog(@"Label的右边坐标:%f,底部坐标:%f",[label right],[label bottom]);
NSLog(@"Label的中心点X坐标:%f,中心点Y坐标:%f",[label centerX],[label centerY]);
NSLog(@"Label的起始点X坐标:%f,起始点Y坐标:%f",[label origin].x,[label origin].y);
}
使用16进制进行颜色设置
a、运行效果

b、功能代码
+ (UIColor *)colorWithHex:(NSString *)string
{
NSString *cleanString = [string stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3)
{
cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
[cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
[cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
[cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
}
if([cleanString length] == 6)
{
cleanString = [cleanString stringByAppendingString:@"ff"];
}
unsigned int baseValue;
[[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
float red = ((baseValue >> 24) & 0xFF)/255.0f;
float green = ((baseValue >> 16) & 0xFF)/255.0f;
float blue = ((baseValue >> 8) & 0xFF)/255.0f;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
c、调用方式
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 300, 200, 50)];
label.backgroundColor = [UIColor colorWithHex:@"#3498c8"];
[self.view addSubview:label];
}
随机颜色
a、运行效果

b、功能代码
+ (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;
}
c、调用方式
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 300, 200, 50)];
label.backgroundColor = [UIColor randomColor];
[self.view addSubview:label];
}
七、UINavigationController
弹出到指定的页面类
- (UIViewController *)popToViewController:(Class)classType
{
for (UIViewController *controller in self.viewControllers)
{
if ([controller isKindOfClass:classType])
{
[self popToViewController:controller animated:YES];
return controller;
}
}
return nil;
}
移除指定的页面类
- (void)removeViewController:(Class)classType currentVC:(UIViewController *)currentVC
{
NSMutableArray *arrayVC = [self.viewControllers mutableCopy];
BOOL isRemove = NO;
// 逆序遍历
for (UIViewController *viewController in [arrayVC reverseObjectEnumerator])
{
if ([viewController isKindOfClass:classType] && currentVC && viewController!=currentVC)
{
[arrayVC removeObject:viewController];
isRemove = YES;
}
}
if (isRemove)
{
[self setViewControllers:arrayVC animated:YES];
}
}
得到需要移除的View
- (NSMutableArray *)getNeedRemoveViewControllers:(NSArray *)array
{
NSMutableArray *arrayVC = [self.viewControllers mutableCopy];
for (UIViewController *viewController in [arrayVC reverseObjectEnumerator])
{
[array enumerateObjectsUsingBlock:^(Class _Nonnull classType, NSUInteger idx, BOOL * _Nonnull stop) {
if ([viewController isKindOfClass:classType])
{
[arrayVC removeObject:viewController];
}
}];
}
return arrayVC;
}
八、UIButton
设置按钮响应区域
调用方式比较特殊,需要使用负数
[self setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -10, -10, -10)];
设置响应区域
- (void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets
{
// 将hitTestEdgeInsets封装为NSValue
NSValue *value = [NSValue value:&hitTestEdgeInsets withObjCType:@encode(UIEdgeInsets)];
// 将value与button通过key关联起来
objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
获取响应区域
- (UIEdgeInsets)hitTestEdgeInsets
{
// 通过key获取到button关联的value(hitTestEdgeInsets)
NSValue *value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS);
if(value)
{
// 从value中取出hitTestEdgeInsets的值
UIEdgeInsets edgeInsets;
[value getValue:&edgeInsets];
return edgeInsets;
}
else
{
return UIEdgeInsetsZero;
}
}
点击区域
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden)
{
return [super pointInside:point withEvent:event];
}
// 响应区域存在,button存在且可以点击
CGRect relativeFrame = self.bounds;
// 偷偷摸摸地修改了按钮的frame
CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);
// 点击的是修改后的frame
return CGRectContainsPoint(hitFrame, point);
}
九、UITableView
滚动到顶部
- (void)scrollToTop
{
[self setContentOffset:CGPointMake(0,0) animated:NO];
}
滚动到底部
- (void)scrollToBottom:(BOOL)animated
{
if (self.contentSize.height > self.frame.size.height)
{
CGPoint pointOffset = CGPointMake(0, self.contentSize.height -self.bounds.size.height);
[self setContentOffset:pointOffset animated:YES];
}
}
十、UIPasteboard
设置剪贴板
+ (void)setContent:(NSString *)text
{
if (text == nil || [text isEqualToString:@""])
{
return;
}
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = text;
}
获取剪贴板
+ (NSString *)content
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
return pasteboard.string;
}
Pod库
XJPCategoryKit
可通过CocoaPods
获得。要安装它,只需在Podfile
中添加以下行:
pod 'XJPCategoryKit'
Demo
Demo在我的Github上,欢迎下载。
FunctionCodeBlock
网友评论