UIButton応答領域の拡大

2261 ワード

  • UIButtonの応答領域は44 x 44 pt
  • 以下であるべきである.

    方法1

  • UIButtonを継承し、Buttonを上書きする方法
  • コードは次のとおりです:
  • - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        if (!self.userInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
            return nil;
        }
        CGRect touchuRect = CGRectInset(self.bounds, -44 , -44);
        if (CGRectContainsPoint(touchuRect, point)) {
            for (UIView *subView in [self.subviews reverseObjectEnumerator]) {
                CGPoint convertedPoint = [subView convertPoint:point toView:self];
                UIView *hinTestView = [subView hitTest:convertedPoint withEvent:event];
                if (hinTestView) {
                    return hinTestView;
                }
            }
            return self;
        }
        return nil;
    }
    

    方法2

  • もUIButtonを継承し、Buttonを上書きする方法
  • である.
  • コードは次のとおりです:
  • - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
    {
        CGRect bounds = self.bounds;
        // 44x44, , 
        CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
        CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
        bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
        return CGRectContainsPoint(bounds, point);
    }
    

    テストをクリックします。コードは次のとおりです。

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.view.backgroundColor = [UIColor whiteColor];
        
        //  
        LXKButton *redButton = [[LXKButton alloc] initWithFrame:CGRectMake(100, 100, 2, 2)];
        redButton.backgroundColor = [UIColor redColor];
        [redButton addTarget:self action:@selector(redButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:redButton];
        
        //  
        LXKButton2 *blackButton = [[LXKButton2 alloc] initWithFrame:CGRectMake(100, 300, 2, 2)];
        blackButton.backgroundColor = [UIColor blackColor];
        [blackButton addTarget:self action:@selector(blackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:blackButton];
    }
    
    - (void)redButtonClicked {
    
        NSLog(@" ");
    }
    
    - (void)blackButtonClicked {
        
        NSLog(@" ");
    }
    
    
  • はcategoryと書いてもいいですか?すべてのbuttonが拡大されているような気がしますが、自分で呼び出さずに実現するのはよくありません.