美文网首页
IOS 常用的工具

IOS 常用的工具

作者: 阳光下的灰尘 | 来源:发表于2021-12-22 17:56 被阅读0次

1、UILabel 间隙

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:label.text];    
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];    
[style setLineSpacing:20];    
[attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, label.text.length)];    
label.attributedText = attrString;

XIB 设置

XIB 设置 UILabel 间隙

UIlabel 的两端对齐

- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{
    if  (self.text == nil || self.text.length == 0) {
        return;
    }

    CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:@{ NSFontAttributeName:self.font } context:nil].size;

    NSInteger length = ( self.text.length - 1 );
    NSString * lastStr = [self.text substringWithRange:NSMakeRange(self.text.length - 1,1)];
    if ([lastStr isEqualToString:@":"] || [lastStr isEqualToString:@":"]) {
        length = (self.text.length-2);
    }
    CGFloat margin = (labelWidth - size.width)/length;
    NSNumber *number = [NSNumber numberWithFloat:margin];
    NSMutableAttributedString * attribute = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attribute addAttribute:NSKernAttributeName value:number range:NSMakeRange(0,length)];
    self.attributedText = attribute;
}

识别 html 标签 并添加 行间距, 如过要设置大小,需要再后面加

    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithData:[self.svfModel.content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attrStr length])];
label.attributedText = attrStr;
label.font = [UIFont systemFontOfSize:16];
    

2、UILabel显示不同颜色字体

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:label.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
label.attributedText = string;

3、 performSelector:withObject:withObject:afterDelay:方法时,需要传入多参数问题

// 方法一、// 把参数放进一个数组/字典,直接把数组/字典当成一个参数传过去,具体方法实现的地方再解析这个数组/字典
NSArray * array =    [NSArray arrayWithObjects: @"first", @"second", nil];
[self performSelector:@selector(fooFirstInput:) withObject: array afterDelay:15.0];
// 方法二、// 使用
NSInvocationSEL aSelector = NSSelectorFromString(@"doSoming:argument2:");    
NSInteger argument1 = 10;    
NSString *argument2 = @"argument2";    
if([self respondsToSelector:aSelector]) {        
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:aSelector]];        
    [inv setSelector:aSelector];        
    [inv setTarget:self];        
    [inv setArgument:&(argument1) atIndex:2];        
    [inv setArgument:&(argument2) atIndex:3];        
    [inv performSelector:@selector(invoke) withObject:nil afterDelay:15.0];    
}

4、比较两个NSDate相差多少小时

NSDate* date1 = someDate; 
NSDate* date2 = someOtherDate; 
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2]; 
double secondsInAnHour = 3600;// 除以3600是把秒化成小时,除以60得到结果为相差的分钟数 
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

5、播放一张张连续的图片

// 加入现在有三张图片分别为animate_1、animate_2、animate_3
// 方法一    
imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], 
                              [UIImage imageNamed:@"animate_2"],
                              [UIImage imageNamed:@"animate_3"]];
imageView.animationDuration = 1.0;
// 方法二    
imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];
// 方法二解释下,这个方法会加载animate_为前缀的,后边0-1024,也就是animate_0、animate_1一直到animate_1024

6、防止离屏渲染为image添加圆角

// 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;
}

7、判断两个rect是否有交叉

if (CGRectIntersectsRect(rect1, rect2)) {}

8、将一个view保存为pdf格式

- (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename{    
    NSMutableData *pdfData = [NSMutableData data];    
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);    
    UIGraphicsBeginPDFPage();    
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();    
    [aView.layer renderInContext:pdfContext];    
    UIGraphicsEndPDFContext();    
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);    
    NSString* documentDirectory = [documentDirectories objectAtIndex:0];    
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];    [pdfData writeToFile:documentDirectoryFilename atomically:YES];    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);}

9、保存UIImage到本地

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

10、键盘上方增加工具栏

UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"                                                               style:UIBarButtonItemStyleBordered target:self                                                              action:@selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
txtField.inputAccessoryView = keyboardDoneButtonView;

11、在image上绘制文字并生成新的image

UIFont *font = [UIFont boldSystemFontOfSize:12];    
UIGraphicsBeginImageContext(image.size);    
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];    
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);    
[[UIColor whiteColor] set];    
[text drawInRect:CGRectIntegral(rect) withFont:font];     
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();

12、圆角矩形

- (void)drawRect:(CGRect)rect {
    // Drawing code
    /*画圆角矩形*/
    float fw = 100;
    float fh = 200;
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextMoveToPoint(context, fw, fh-4);  // 开始坐标右边开始
    CGContextAddArcToPoint(context, fw, fh, fw-4, fh, 4);  // 右下角角度
    CGContextAddArcToPoint(context, 100-16, fh, 100-16, fh-4, 4); // 左下角角度
    CGContextAddArcToPoint(context, 100-16, 200-8, fw-4, 200-8, 4); // 左上角
    CGContextAddArcToPoint(context, fw, 200-8, fw, fh-4, 4); // 右上角
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
}

每隔4个字符添加一个空格的字符串算法

//每隔4个字符添加一个空格的字符串算法
- (NSString *)dealWithString:(NSString *)number
{
    NSString *doneTitle = @"";
    int count = 0;
    for (int i = 0; i < number.length; i++) {

        count++;
        doneTitle = [doneTitle stringByAppendingString:[number substringWithRange:NSMakeRange(i, 1)]];
        if (count == 4) {
            doneTitle = [NSString stringWithFormat:@"%@ ", doneTitle];
            count = 0;
        }
    }
    NSLog(@"%@", doneTitle);
    return doneTitle;
}

获取 UIAlertControll 中 TitleLabel 和 ContentLabel

        UIView *subView1 = alert.view.subviews.firstObject;
        UIView *subView2 = subView1.subviews.firstObject;
        UIView *subView3 = subView2.subviews.firstObject;
        UIView *subView4 = subView3.subviews.firstObject;
        UIView *subView5 = subView4.subviews.firstObject;
        
        //取title和message:
        UILabel *titleLab = subView5.subviews[1];
        UILabel *messageLab = subView5.subviews[2];
        titleLab.wlAccessibilityLabel = titleLab.text;
        messageLab.wlAccessibilityLabel = messageLab.text;

相关文章

网友评论

      本文标题:IOS 常用的工具

      本文链接:https://www.haomeiwen.com/subject/mxpqqrtx.html