/* Inset `rect' by `(dx, dy)' -- i.e., offset its origin by `(dx, dy)', and
decrease its size by `(2*dx, 2*dy)'. */
CG_EXTERN CGRect CGRectInset(CGRect rect, CGFloat dx, CGFloat dy)
CG_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);
以rect为基准,x,y变化dx,dy,size减少2*dx,2*dy
eg1:CGRect _rect=CGRectInset(self.frame, -100, -100);
result:po self.frame
(origin = (x = 0, y = 100), size = (width = 300, height = 100))
po _rect
(origin = (x = -100, y = 0), size = (width = 500, height = 300))
eg2:CGRect _rect=CGRectInset(self.bounds, -100, -100)
result:po self.bounds
(origin = (x = 0, y = 0), size = (width = 300, height = 100))
po _rect
(origin = (x = -100, y = -100), size = (width = 500, height = 300))
/* Offset `rect' by `(dx, dy)'. */
CG_EXTERN CGRect CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy)
CG_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);
x,y变化的dx,dy,size不变
eg1:CGRect _rect=CGRectOffset(self.bounds, 100, 100);
result:po self.bounds
(origin = (x = 0, y = 0), size = (width = 300, height = 100))
po _rect
(origin = (x = 100, y = 100), size = (width = 300, height = 100))
有时候我们需要修改控件的背景透明度,但是子控件默认
回继承父控件的透明度属性,此时可以这样干
self.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.1];
父视图调用hitTest:withEvent:在内部首先会判断该视图是否能响应触摸事件,如果不能响应,返回nil,表示该视图不响应此触摸事件。然后再调用pointInside:withEvent:(该方法用来判断点击事件发生的位置是否处于当前视图范围内)。如果pointInside:withEvent:返回NO,那么hiteTest:withEvent:也直接返回nil。
如果pointInside:withEvent:返回YES,则向当前视图的所有子视图发送hitTest:withEvent:消息,所有子视图的遍历顺序是从最顶层视图一直到到最底层视图,即从subviews数组的末尾向前遍历。直到有子视图返回非空对象或者全部子视图遍历完毕;若第一次有子视图返回非空对象,则 hitTest:withEvent:方法返回此对象,处理结束;如所有子视图都返回非,则hitTest:withEvent:方法返回该视图自身。
hitTest:withEvent:的底层实现:
// point是该视图的坐标系上的点
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
// 1.判断自己能否接收触摸事件
if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) return nil;
// 2.判断触摸点在不在自己范围内
if (![self pointInside:point withEvent:event]) return nil;
// 3.从后往前遍历自己的子控件,看是否有子控件更适合响应此事件
int count = self.subviews.count;
for (int i = count - 1; i >= 0; i--) {
UIView *childView = self.subviews[i];
CGPoint childPoint = [self convertPoint:point toView:childView];
UIView *fitView = [childView hitTest:childPoint withEvent:event];
if (fitView) {
return fitView;
}
}
// 没有找到比自己更合适的view
return self;
}
eg1:需求,用户名和评论内容放到一起,要求用户名可点击
重写button的下面的方法
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGRect _rect=CGRectMake(0, 0, 50, 50);
if (CGRectContainsPoint(_rect, point)) {
return self;
}else{
return nil;
}
}