objectivec dispatch_semaphore_t

异步方法同步执行:信号量dispatch_semaphore

dispatch_semaphore_t
- (NSInteger)methodSync {
    
    NSLog(@"methodSync Begin");
    __block NSInteger result = 0;
    //使用信号量dispatch_semaphore
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [self methodAsync:^(NSInteger value) {
        result = value;
        dispatch_semaphore_signal(sema);
    }];
    // 这里本来同步方法会立即返回,但信号量=0使得线程阻塞
    // 当异步方法回调之后,发送信号,信号量变为1,这里的阻塞将被解除,从而返回正确的结果
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    return result;
}

objectivec NSInvocation的

NSInvocation创建和调用

NSInvocation
// create
- (NSInvocation*)createInvocationWithSelector:(SEL)selector {
    
    NSMethodSignature *signature = [self methodSignatureForSelector:selector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.target = self;
    invocation.selector = selector;
    return invocation;
}
//invoke
    NSInvocation *invocation = self.eventStrategy[eventName]; // dict包装多个invocation
    [invocation setArgument:&userInfo atIndex:2]; // 参数
    [invocation invoke];

objectivec navigationShouldPopOnBackButton

.m
/// 导航返回时跳过的控制器数目
@property (assign, nonatomic) NSInteger navSkipCount;

- (BOOL)navigationShouldPopOnBackButton {
    NSArray *navStack = self.navigationController.viewControllers;
    [self.navigationController popToViewController:navStack[navStack.count - 2 - self.navSkipCount] animated:YES];
    return NO;
}

objectivec 渐变蒙层

HTVGradientLayer.h
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN
//渐变蒙层
@interface HTVGradientLayer : UIView

@end

NS_ASSUME_NONNULL_END
HTVGradientLayer.m
#import "HTVGradientLayer.h"

@interface HTVGradientLayer ()

@property (nonatomic, strong) CAGradientLayer *gradientLayer;

@end

@implementation HTVGradientLayer

- (instancetype)init
{
    
    self = [super init];
    if (self) {
        
        [self initLayerMask];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        [self initLayerMask];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    
    self = [super initWithCoder:aDecoder];
    if (self) {
        
        [self initLayerMask];
    }
    return self;
}

- (void)initLayerMask
{
    
    self.layer.mask = self.gradientLayer;
}

- (CAGradientLayer *)gradientLayer
{
    
    if (_gradientLayer == nil) {
        _gradientLayer = [[CAGradientLayer alloc] init];
        _gradientLayer.colors = @[(__bridge id)[[UIColor blackColor] colorWithAlphaComponent:0.2].CGColor,(__bridge id)[UIColor blackColor].CGColor];
        _gradientLayer.locations = @[@0.0, @0.2,@1.0];
    }
    return _gradientLayer;
}


- (void)layoutSublayersOfLayer:(CALayer *)layer
{
    
    [super layoutSublayersOfLayer:layer];
    
    _gradientLayer.frame = self.bounds;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    self.gradientLayer.frame = self.bounds;
    [CATransaction commit];
}

@end

objectivec 有图片文字AttributedString

有图片文字AttributedString

AttributedString
- (NSAttributedString *)bounusString:(NSString *)bounusText
{
    NSMutableAttributedString *msg = [[NSMutableAttributedString alloc] init];
    UIFont *textFont = [UIFont fontWithName:@"Roboto-Regular" size:13];
    
    NSTextAttachment *dimondAttachment = [[NSTextAttachment alloc] init];
    dimondAttachment.image = [UIImage imageNamed:@"ico_dimond"];
    dimondAttachment.bounds = CGRectMake(0, 0, 13, 13);
    NSAttributedString *dimondatrri = [NSAttributedString attributedStringWithAttachment:dimondAttachment];
    [msg appendAttributedString:dimondatrri];
    
    NSString *bounus = [NSString stringWithFormat:NSLocalizedString(@"xxx", @"xxx"),bounusText];
    NSString *bounusString = [NSString stringWithFormat:@" %@  ",bounus];
    NSMutableAttributedString *bounes = [[NSMutableAttributedString alloc] initWithString:bounusString];
    [bounes addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#F8E71C"],NSFontAttributeName:textFont} range:NSMakeRange(0, bounes.string.length)];
    [msg appendAttributedString:bounes];
    
    
    NSTextAttachment *yellowAttachment = [[NSTextAttachment alloc] init];
    yellowAttachment.image = [[UIImage imageNamed:@"xxx"] rtl_imageFlippedForRightToLeftLayoutDirection];
    yellowAttachment.bounds = CGRectMake(0, 0, 10, 10);
    NSAttributedString *yellowAtrri = [NSAttributedString attributedStringWithAttachment:yellowAttachment];
    [msg appendAttributedString:yellowAtrri];
    
    [msg addAttribute:NSWritingDirectionAttributeName
                              value:@[ @(NSWritingDirectionEmbedding | isRTLInterface() ? NSWritingDirectionRightToLeft : NSWritingDirectionLeftToRight) ]
                              range:NSMakeRange(0, msg.length)];
    
    return [msg copy];
}

objectivec 格式化显示数字,单位变化

格式化显示数字,单位变化<br/> 1 <n <1000显示源数字n <br/> 1000 <n <1000000显示(n / 1000)k保留二位小数<br/> 1000000 <n显示(n / 1000000)m保留二位小数<br/> @param amount数值<br/> @return格式化后的输出

1
- (NSString *)numberFormat:(NSInteger)amount
{
    NSInteger number = amount;
    if        (number >= 1000000) {
        
        NSString *str = [NSString stringWithFormat:@"%.2fM", (number - number % 10000) / 1000000.];
        
        return str;
        
    } else if (amount >= 1000) {
        
        NSString *str = [NSString stringWithFormat:@"%.2fK", (number - number % 10) / 1000.];
        
        return str;
    }
    
    return [NSString stringWithFormat:@"%@", @(amount)];
}

objectivec attributedLabel

.m
#import "TTTAttributedLabel.h"

@interface StudyServiceVC () <TTTAttributedLabelDelegate>

@property (weak, nonatomic) IBOutlet TTTAttributedLabel *labelTip;

    self.labelTip.linkAttributes = @{NSForegroundColorAttributeName:HEXCOLOR(0x22CB91), NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)};
    self.labelTip.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    self.labelTip.delegate = self;
    self.labelTip.text = @"如果服务地址有误,请通过意见反馈发给我们,方便我们修改!";
    NSRange range = [self.labelTip.text rangeOfString:@"意见反馈"];
    [self.labelTip addLinkToURL:[NSURL URLWithString:@"feedback"] withRange:range];

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    if ([url.absoluteString isEqualToString:@"feedback"]) {
        [self.navigationController pushViewController:FeedbackVC.new animated:YES];
    }
}

objectivec 照片视图

.m
@interface PostLoanVC () <HXPhotoViewDelegate>

@property (weak, nonatomic) IBOutlet HXPhotoView *photoView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintPhotoViewHeight;

    self.photoView.addImageName = @"detail_button_add";
    self.photoView.lineCount = 5;
    self.photoView.delegate = self;
    self.photoView.manager.configuration.restoreNavigationBar = YES;
    self.photoView.manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;

- (void)photoView:(HXPhotoView *)photoView updateFrame:(CGRect)frame {
    if (photoView == self.photoView) {
        [UIView animateWithDuration:0.25 animations:^{
            self.constraintPhotoViewHeight.constant = frame.size.height;
            [self.view layoutIfNeeded];
        }];
    }
}

        NSMutableArray<UIImage *> *images = [NSMutableArray new];
        NSMutableArray<NSString *> *imageNames = [NSMutableArray new];
        for (int i = 0; i < self.photoView.manager.afterSelectedArray.count; i++) {
            HXPhotoModel *model = self.photoView.manager.afterSelectedArray[i];
            UIImage *image = [Util getImageFromHXPhotoModel:model];
            [images addObject:image];
            NSString *imageName = [NSString stringWithFormat:@"topicimg-%@.png", [NSUUID UUID].UUIDString];
            [imageNames addObject:imageName];
        }

objectivec 照片选择器

.m
#import "HXPhotoPicker.h"

@property (strong, nonatomic) HXPhotoManager *manager;

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.restoreNavigationBar = YES;
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;

        _manager.configuration.singleSelected = YES;
        _manager.configuration.singleJumpEdit = YES;
        _manager.configuration.movableCropBox = YES;
        _manager.configuration.movableCropBoxEditSize = YES;
        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
    }
    return _manager;
}

    @weakify(self);
    [self hx_presentSelectPhotoControllerWithManager:self.manager didDone:^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL isOriginal, UIViewController *viewController, HXPhotoManager *manager) {
        @strongify(self);
        HXPhotoModel *model = allList.firstObject;
        UIImage *image = [Util getImageFromHXPhotoModel:model];
        self.imageAvatar.image = image;
    } cancel:^(UIViewController *viewController, HXPhotoManager *manager) {
        
    }];

objectivec 徽章

.m
#import "WZLBadgeImport.h"

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    self.messageButtonItem.badgeCenterOffset = CGPointMake(-10, 5);
    self.messageButtonItem.badgeFont = [UIFont systemFontOfSize:12];
    self.messageButtonItem.badgeBgColor = HEXCOLOR(0xFF7159);
    self.messageButtonItem.badgeTextColor = HEXCOLOR(0xFFFFFF);
    [self.messageButtonItem showBadgeWithStyle:WBadgeStyleNumber value:333 animationType:WBadgeAnimTypeNone];
}