/* 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為基準(zhǔn),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))
有時(shí)候我們需要修改控件的背景透明度,但是子控件默認(rèn)
回繼承父控件的透明度屬性铐懊,此時(shí)可以這樣干
self.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.1];
父視圖調(diào)用hitTest:withEvent:在內(nèi)部首先會(huì)判斷該視圖是否能響應(yīng)觸摸事件邀桑,如果不能響應(yīng),返回nil科乎,表示該視圖不響應(yīng)此觸摸事件壁畸。然后再調(diào)用pointInside:withEvent:(該方法用來判斷點(diǎn)擊事件發(fā)生的位置是否處于當(dāng)前視圖范圍內(nèi))。如果pointInside:withEvent:返回NO,那么hiteTest:withEvent:也直接返回nil捏萍。
如果pointInside:withEvent:返回YES太抓,則向當(dāng)前視圖的所有子視圖發(fā)送hitTest:withEvent:消息,所有子視圖的遍歷順序是從最頂層視圖一直到到最底層視圖令杈,即從subviews數(shù)組的末尾向前遍歷腻异。直到有子視圖返回非空對(duì)象或者全部子視圖遍歷完畢;若第一次有子視圖返回非空對(duì)象这揣,則 hitTest:withEvent:方法返回此對(duì)象悔常,處理結(jié)束;如所有子視圖都返回非给赞,則hitTest:withEvent:方法返回該視圖自身机打。
hitTest:withEvent:的底層實(shí)現(xiàn):
// point是該視圖的坐標(biāo)系上的點(diǎn)
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
// 1.判斷自己能否接收觸摸事件
if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) return nil;
// 2.判斷觸摸點(diǎn)在不在自己范圍內(nèi)
if (![self pointInside:point withEvent:event]) return nil;
// 3.從后往前遍歷自己的子控件,看是否有子控件更適合響應(yīng)此事件
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:需求片迅,用戶名和評(píng)論內(nèi)容放到一起残邀,要求用戶名可點(diǎn)擊
重寫button的下面的方法
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGRect _rect=CGRectMake(0, 0, 50, 50);
if (CGRectContainsPoint(_rect, point)) {
return self;
}else{
return nil;
}
}