hitTest:方法练习 - 不规则区域点击事件处理

1.


2.自定义Button

//
//  PopBtn.m


#import "PopBtn.h"

@implementation PopBtn

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    
    // 当前控件上的点转换到chatView上
    CGPoint chatP = [self convertPoint:point toView:self.chatView];
    
    // 判断下点在不在chatView上
    if ([self.chatView pointInside:chatP withEvent:event]) {
        return self.chatView;
    }else{
        return [super hitTest:point withEvent:event];
    }
    
    
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获取UITouch
    UITouch *touch = [touches anyObject];
    
    // 获取当前的点
    CGPoint curP = [touch locationInView:self];
    
    // 获取上一个的点
    CGPoint preP = [touch previousLocationInView:self];
    
    // 获取偏移量
    CGFloat offsetX = curP.x - preP.x;
    CGFloat OffsetY = curP.y - preP.y;
    
    // 修改控件的位置
    CGPoint center = self.center;
    center.x += offsetX;
    center.y += OffsetY;
    
    self.center = center;
    
}
@end

3.点击按钮,弹出

#import "ViewController.h"
#import "PopBtn.h"

@interface ViewController ()

@end

@implementation ViewController
- (IBAction)popChatView:(PopBtn *)sender {
    // 弹出对话框
    UIButton *chatView = [UIButton buttonWithType:UIButtonTypeCustom];
    
    chatView.bounds = CGRectMake(0, 0, 200, 200);
    chatView.center = CGPointMake(100, -100);
    
    [chatView setBackgroundImage:[UIImage imageNamed:@"对话框"] forState:UIControlStateNormal];
    [chatView setBackgroundImage:[UIImage imageNamed:@"小孩"] forState:UIControlStateHighlighted];
    sender.chatView = chatView;
    [sender addSubview:chatView];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


@end
演示:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值