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

来源:互联网 发布:软件流量是什么 编辑:程序博客网 时间:2024/05/28 17:05

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