美文网首页常用代码备份
Masonry给ScrollView添加约束/UIImageVi

Masonry给ScrollView添加约束/UIImageVi

作者: LD_左岸 | 来源:发表于2019-04-08 11:58 被阅读0次
//
//  ScrollViewController.m
//  展开合起
//
//  Created by 李洞洞 on 2019/4/8.
//  Copyright © 2019年 李洞洞. All rights reserved.
//

#import "ScrollViewController.h"
#import "Masonry.h"
@interface ScrollViewController ()
@property(nonatomic,strong)UIScrollView * scrollView;
@end

@implementation ScrollViewController
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.backgroundColor = [UIColor cyanColor];
        if (@available(iOS 11.0, *)) {
            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _scrollView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.top.and.bottom.mas_equalTo(self.view);
    }];
#pragma mark --- 子1
    UIView * view = ({
        UIView * view  = [[UIView alloc]init];
        view.backgroundColor = [UIColor purpleColor];
        view;
    });
    [self.scrollView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.scrollView).mas_offset(0);
        make.top.mas_equalTo(self.scrollView.mas_top).mas_offset(10);
        make.height.mas_equalTo(250);
        make.width.mas_equalTo(self.scrollView.mas_width);
    }];
#pragma mark --- 子2
    UIView * two = ({
        UIView * view = [[UIView alloc]init];
        view.backgroundColor = [UIColor orangeColor];
        view;
    });
    [self.scrollView addSubview:two];
    [two mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.scrollView).mas_offset(0);
        make.top.mas_equalTo(view.mas_bottom).mas_offset(10);
        make.height.mas_equalTo(350);
        make.width.mas_equalTo(self.scrollView.mas_width);
    }];
#pragma mark --- 子3
    UIView * three = ({
        UIView * view = [[UIView alloc]init];
        view.backgroundColor = [UIColor redColor];
        view;
    });
    [self.scrollView addSubview:three];
    [three mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.scrollView).mas_offset(0);
        make.top.mas_equalTo(two.mas_bottom).mas_offset(10);
        make.height.mas_equalTo(350);
        make.width.mas_equalTo(self.scrollView.mas_width);
    }];
    [self.view layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.frame), CGRectGetMaxY(three.frame) + 10);

}

@end

E77157CA4119979301B856970CD9DD01.png

ImageView四周加阴影效果

Simulator Screen Shot - iPhone 7 - 2019-10-18 at 13.45.45.png
UIImageView * middleCenterShaowBgImv = ({
        UIImageView * imv = [[UIImageView alloc]init];
        imv.image = [UIImage imageNamed:@"Information1-card"];
        CALayer * layer = [imv layer];
        layer.borderColor = [[UIColor clearColor] CGColor];
        layer.borderWidth = 5.0f;
        imv.layer.shadowColor = [UIColor grayColor].CGColor;
        imv.layer.shadowOffset = CGSizeMake(0, 0);
        imv.layer.shadowOpacity = 0.3;
        imv.layer.shadowRadius = 10.0;
        imv.backgroundColor = UIColor.whiteColor
        imv;
    });
    [middleView addSubview:middleCenterShaowBgImv];
    [middleCenterShaowBgImv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(24);
        make.top.mas_offset(22);
        make.right.mas_offset(-24);
        make.bottom.mas_offset(-27);
    }];

UIView局部角切圆角

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
                                                   byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath; 
self.layer.mask = maskLayer;

属性字符串加点击事件

    // 测试文本
    NSString *text = @"感谢您选择敏特研学院App!\n我们非常重视您的个人信息和隐私保护,为了更好的保障您的个人权益,在您使用我们的产品前,请您务必审慎阅读《用户协议和隐私政策》内的所有条款,尤其是:\n1. 我们对您的个人信息的收集/保存/使用以及您的用户权利等条款;\n2.约定我们的限制责任,免责条款.\n\n您点击\"同意\"的行为即表示您已阅读完毕并同意以上协议的全部内容.";

    // 转成可变属性字符串
    NSMutableAttributedString * mAttributedString = [NSMutableAttributedString new];

    // 调整行间距段落间距
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
        [paragraphStyle setLineSpacing:2];
        [paragraphStyle setParagraphSpacing:4];

    // 设置文本属性
    NSDictionary *attri = [NSDictionary dictionaryWithObjects:@[[UIFont systemFontOfSize:16], [UIColor blackColor], paragraphStyle] forKeys:@[NSFontAttributeName, NSForegroundColorAttributeName, NSParagraphStyleAttributeName]];
        [mAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text attributes:attri]];

    // 匹配条件
    NSString *regulaStr = @"《用户协议和隐私政策》";

    NSError *err = NULL;
    // 根据匹配条件,创建了一个正则表达式
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&err];
        if (!regex) {
            NSLog(@"正则创建失败error!= %@", [err localizedDescription]);
        } else {
            NSArray *allMatches = [regex matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
            for (NSTextCheckingResult *match in allMatches) {
                NSString *substrinsgForMatch2 = [mAttributedString.string substringWithRange:match.range];
                NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:substrinsgForMatch2];
                // 利用YYText设置一些文本属性
                one.yy_font = [UIFont systemFontOfSize:16];
                one.yy_underlineStyle = NSUnderlineStyleSingle;
                one.yy_color = [UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000];
                
                YYTextBorder *border = [YYTextBorder new];
                border.cornerRadius = 3;
                border.insets = UIEdgeInsetsMake(-2, -1, -2, -1);
                border.fillColor = [UIColor colorWithWhite:0.000 alpha:0.220];
                
                YYTextHighlight *highlight = [YYTextHighlight new];
                [highlight setBorder:border];
                [one yy_setTextHighlight:highlight range:one.yy_rangeOfAll];
                // 根据range替换字符串
                [mAttributedString replaceCharactersInRange:match.range withAttributedString:one];
            }
        }

        // 使用YYLabel显示
        YYLabel *label = [YYLabel new];
        label.userInteractionEnabled = YES;
        label.numberOfLines = 0;
        label.textVerticalAlignment = YYTextVerticalAlignmentTop;
//        label.size = CGSizeMake(260, 260);
//        label.center = CGPointMake(self.view.width / 2, 200);
        label.attributedText = mAttributedString;
//        [self.view addSubview:label];
        label.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            NSString *string = [NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]];
            NSLog(@"%@", string);
            if (self.confimBlock) {
                self.confimBlock(self);
            }
        };

    // 利用YYTextLayout计算高度
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(SCREEN_WIDTH - 60, MAXFLOAT)];
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text: mAttributedString];
//    label.height = textLayout.textBoundingSize.height;
    [self.alertV addSubview:label];
//    label.backgroundColor = UIColor.cyanColor;
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(textLayout.textBoundingSize.height);
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_equalTo(self.mainTitleLabel.mas_bottom).mas_offset(25);
    }];

属性字符串拼接图片

NSMutableAttributedString * attr = [[NSMutableAttributedString alloc]initWithString:unFinishCount attributes:@{NSForegroundColorAttributeName: UIColor.whiteColor,NSFontAttributeName : [UIFont systemFontOfSize:10]}];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed: @"关闭按钮"];
textAttachment.bounds = CGRectMake(0, -1, 10, 10);
NSAttributedString * attachAttr = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attr appendAttributedString:attachAttr];
self.unLabel.textAlignment = NSTextAlignmentCenter;
self.unLabel.attributedText = attr;

给一组cell加阴影

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 圆角角度
    CGFloat radius = 10.f;
    // 设置cell 背景色为透明
    cell.backgroundColor = UIColor.clearColor;
    // 创建两个layer
    CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
    CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
    // 获取显示区域大小
    CGRect bounds = CGRectInset(cell.bounds, SCREEN_WIDTH / 375 * 20, 0);
    // cell的backgroundView
    UIView *normalBgView = [[UIView alloc] initWithFrame:bounds];
    // 获取每组行数
    NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
    // 贝塞尔曲线
    UIBezierPath *bezierPath = nil;
    
    if (rowNum == 1) {
        // 一组只有一行(四个角全部为圆角)
        bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
        normalBgView.clipsToBounds = NO;
    }else {
        normalBgView.clipsToBounds = YES;
        if (indexPath.row == 0) {
            normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(-5, 0, 0, 0));
            CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(5, 0, 0, 0));
            // 每组第一行(添加左上和右上的圆角)
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(radius, radius)];
        }else if (indexPath.row == rowNum - 1) {
            normalBgView.frame = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, -5, 0));
            CGRect rect = UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(0, 0, 5, 0));
            // 每组最后一行(添加左下和右下的圆角)
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight) cornerRadii:CGSizeMake(radius, radius)];
        }else {
            // 每组不是首位的行不设置圆角
            bezierPath = [UIBezierPath bezierPathWithRect:bounds];
        }
    }
    
    // 阴影
    normalLayer.shadowColor = [UIColor blackColor].CGColor;
    normalLayer.shadowOpacity = 0.2;
    normalLayer.shadowOffset = CGSizeMake(0, 0);
    normalLayer.path = bezierPath.CGPath;
    normalLayer.shadowPath = bezierPath.CGPath;
    
    // 把已经绘制好的贝塞尔曲线路径赋值给图层,然后图层根据path进行图像渲染render
    normalLayer.path = bezierPath.CGPath;
    selectLayer.path = bezierPath.CGPath;
    
    // 设置填充颜色
    normalLayer.fillColor = [UIColor whiteColor].CGColor;
    // 添加图层到nomarBgView中
    [normalBgView.layer insertSublayer:normalLayer atIndex:0];
    normalBgView.backgroundColor = UIColor.clearColor;
    cell.backgroundView = normalBgView;
    
    // 替换cell点击效果
    UIView *selectBgView = [[UIView alloc] initWithFrame:bounds];
    selectLayer.fillColor = [UIColor colorWithWhite:0.95 alpha:1.0].CGColor;
    [selectBgView.layer insertSublayer:selectLayer atIndex:0];
    selectBgView.backgroundColor = UIColor.clearColor;
    cell.selectedBackgroundView = selectBgView;
}

让TableViewCell既有圆角又有阴影

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:self.titleL];
        [self.contentView addSubview:self.tableView];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
#if 1
        self.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];
        self.contentView.layer.cornerRadius = 6;
        self.contentView.backgroundColor = UIColor.whiteColor;
        self.contentView.layer.shadowColor = [UIColor grayColor].CGColor;
        self.contentView.layer.shadowOffset = CGSizeMake(0, 0);
        self.contentView.layer.shadowOpacity = 0.3;
        self.contentView.layer.shadowRadius = 10.0;
#endif
    }
    return self;
}

播放Gif的正确姿势

import <ImageIO/ImageIO.h>

- (void)viewDidLoad {
    [super viewDidLoad];
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://bigfish-img-test.oss-cn-hangzhou.aliyuncs.com/media/res/confres/course/image/contentpic/exercise/test/right_l.gif"]];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    size_t count = CGImageSourceGetCount(source);
    UIImage *animatedImage;
    NSMutableArray * imageArr = [NSMutableArray array];
    NSTimeInterval duration = 0.0f;
    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
    }
    else {
        for (size_t i = 0; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
            [imageArr addObject:[UIImage imageWithCGImage:image]];
            duration += [self sd_frameDurationAtIndex:i source:source];
            CGImageRelease(image);
        }
        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }
        NSLog(@"%f --- %@",duration,imageArr);
    }
    CFRelease(source);
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 310, 280)];
    [self.view addSubview:imageView];
    imageView.animationImages = imageArr;
    imageView.animationDuration = duration;
    imageView.animationRepeatCount = 1;
    [imageView startAnimating];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        imageView.hidden = YES;
    });
}
- (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float frameDuration = 0.1f;
    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTimeUnclampedProp) {
        frameDuration = [delayTimeUnclampedProp floatValue];
    }
    else {
        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTimeProp) {
            frameDuration = [delayTimeProp floatValue];
        }
    }
    if (frameDuration < 0.011f) {
        frameDuration = 0.100f;
    }
    CFRelease(cfFrameProperties);
    return frameDuration;
}

判断ScrollView CollectionView的滑动方向

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint scrollVelocity = [scrollView.panGestureRecognizer  translationInView:self.view];
    if (scrollVelocity.x < 0) {
        if (self.ldIndex == self.models.count) {
            LDLog(@"最后一页 再往后滑事件....");
            self.first = YES;
        }
    }else{
        self.first = NO;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.index = scrollView.contentOffset.x / SCREEN_WIDTH;
    self.ldIndex = self.index + 1;
    if (self.first) {
        [[NSNotificationCenter defaultCenter] postNotificationName:ExerciseQsSectionEndNotifcation object:nil userInfo:nil];
      }
}

UICollectionView滑动时有间隔

DCB4420A38C41EF7A815990269152C7E.png
- (UICollectionView *)collection
{
    if (!_collection) {
        _collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, UIScreen.mainScreen.bounds.size.height) collectionViewLayout:[[LDFlowLayout alloc]init]];
        _collection.dataSource = self;
        [_collection registerClass:[LDDCollectionViewCell class] forCellWithReuseIdentifier:@"LDD"];
    }
    return _collection;
}

@implementation LDFlowLayout

- (void)prepareLayout
{
    [super prepareLayout];
    self.minimumLineSpacing = 0;
    self.minimumInteritemSpacing = 0;
    self.collectionView.pagingEnabled = YES;
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.itemSize = CGSizeMake(self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
    self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
@end
- (void)loadView
{
    [super loadView];
    CGRect rect = self.view.frame;
    rect.size.width += 20;
    self.view.frame = rect;
}
@implementation LDDCollectionViewCell
- (UIView *)ld_contentView
{
    if (!_ld_contentView) {
        _ld_contentView = [[UIView alloc]init];
    }
    return _ld_contentView;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self.contentView addSubview:self.ld_contentView];
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.ld_contentView.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height);
}
@end

图片灰度化处理

-(UIImage*)getGrayImage:(UIImage*)sourceImage
{
    int width = sourceImage.size.width*sourceImage.scale;
    int height = sourceImage.size.height*sourceImage.scale;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGBitmapByteOrderDefault);
    CGColorSpaceRelease(colorSpace);
    
    if (context == NULL) {
        return nil;
    }
    
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);
    CGImageRef cgImage=CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    
    CGContextRelease(context);
    
    return grayImage;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    UIImageView * imv = ({
        UIImageView * image = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
        image.image = [UIImage imageNamed:@"999.jpg"];
        image;
    });
    [self.view addSubview:imv];
    
    UIImageView * imv1 = ({
        UIImageView * image = [[UIImageView alloc]initWithFrame:CGRectMake(100, 220, 100, 100)];
        image.image = [self getGrayImage:[UIImage imageNamed:@"999.jpg"]];
        image;
    });
    [self.view addSubview:imv1];
}
3A8FE022-E20A-4D2E-833A-02D7CC906281.png

递归 巧妙匹配重复子串

NSString *baseStr = @"...我是....是,,,,,...我是,,.是,,..我是...不...是,,,,.我...,,我是..";
NSString *aimStr = @"我是";
NSMutableArray *result = [NSMutableArray array];
result =  [self findAimstrAllRangeWithBaseStr:baseStr andAimStr:aimStr andBaseRange:NSMakeRange(0, baseStr.length) resultArr:result];
NSLog(@"%@",result);



-(NSMutableArray *)findAimstrAllRangeWithBaseStr:(NSString *)baseStr andAimStr:(NSString*)aimStr andBaseRange:(NSRange)baseRange resultArr:(NSMutableArray *)resultArr
{
    // 区分大小写比较
    NSRange range = [baseStr rangeOfString:aimStr options:NSLiteralSearch range:baseRange];
    
    if (range.length > 0) {
        [resultArr addObject:NSStringFromRange(range)];
        NSUInteger nextLocation = range.location + range.length;
        NSRange rangeNew = NSMakeRange(nextLocation, baseStr.length - nextLocation);
        [self findAimstrAllRangeWithBaseStr:baseStr andAimStr:aimStr andBaseRange:rangeNew resultArr:resultArr];
    }
    return resultArr;
}

相关文章

网友评论

    本文标题:Masonry给ScrollView添加约束/UIImageVi

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