UIButton

2017-04-26  本文已影响0人  夜雨聲煩_

1.设置额外热区

使用:UIButton+TouchAreaInsets
调用属性方法:

@property (nonatomic, assign) UIEdgeInsets touchAreaInsets;

内部实现:

#import <objc/runtime.h>
#import "UIButton+TouchAreaInsets.h"


@implementation UIButton (JLUtils)

- (UIEdgeInsets)touchAreaInsets
{
    return [objc_getAssociatedObject(self, @selector(touchAreaInsets)) UIEdgeInsetsValue];
}
/**
 *  @brief  设置按钮额外热区
 */
- (void)setTouchAreaInsets:(UIEdgeInsets)touchAreaInsets
{
    NSValue *value = [NSValue valueWithUIEdgeInsets:touchAreaInsets];
    objc_setAssociatedObject(self, @selector(touchAreaInsets), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    UIEdgeInsets touchAreaInsets = self.touchAreaInsets;
    CGRect bounds = self.bounds;
    bounds = CGRectMake(bounds.origin.x - touchAreaInsets.left,
                        bounds.origin.y - touchAreaInsets.top,
                        bounds.size.width + touchAreaInsets.left + touchAreaInsets.right,
                        bounds.size.height + touchAreaInsets.top + touchAreaInsets.bottom);
    return CGRectContainsPoint(bounds, point);
}

@end

2.结合NSTimer的倒计时按钮

使用:UIButton+HWTimer
调用方法:

- (void)countDownFromTime:(NSInteger)startTime unitTitle:(NSString *)unitTitle normalTitle:(NSString *)normalTitle comlation:(dispatch_block_t)complation;

内部实现:

- (void)countDownFromTime:(NSInteger)startTime unitTitle:(NSString *)unitTitle normalTitle:(NSString *)normalTitle comlation:(dispatch_block_t)complation
{
    __weak typeof(self) weakSelf = self;
    __block NSInteger remainTime = startTime;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
      if (remainTime <= 0) {
          dispatch_source_cancel(timer);
          dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.enabled = YES;
            [weakSelf setTitle:normalTitle forState:UIControlStateNormal];
            if (complation) {
                complation();
            }
          });
      }
      else {
          NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)remainTime];
          dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf setTitle:[NSString stringWithFormat:@"%@%@", timeStr, unitTitle] forState:UIControlStateDisabled];
            weakSelf.enabled = NO;
          });
          remainTime--;
      }
    });
    dispatch_resume(timer);
}
上一篇下一篇

猜你喜欢

热点阅读