UIEdgeInsets

定义

typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;

创建

UIKIT_STATIC_INLINE UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {
    UIEdgeInsets insets = {top, left, bottom, right};
    return insets;
}

 

UIButton有相关属性:XXXEdgeInsets.这些属性可以控制UIButton显示内容的具体frame。

@property(nonatomic)          UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero
@property(nonatomic)          UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero
@property(nonatomic)          UIEdgeInsets imageEdgeInsets;   

实现

UIEdgeInsets主要和CGRect产生作用。

具体操作就是如下所示

UIKIT_STATIC_INLINE CGRect UIEdgeInsetsInsetRect(CGRect rect, UIEdgeInsets insets) {
    rect.origin.x    += insets.left;//x轴右移left个单位(left<0时则左移)
    rect.origin.y    += insets.top;//y轴下移top个单位(top<0时则上移)
    rect.size.width  -= (insets.left + insets.right);//宽减少left+right
    rect.size.height -= (insets.top  + insets.bottom);//高减少top+bottom
    return rect;
}

这里需要注意的就是顺序问题。定义中是UIEdgeInsets insets = {top, left, bottom, right}; 

而到了UIEdgeInsetsInsetRec从上往下的顺序则是

  1. left
  2. top
  3. left+right
  4. top+ bottom

例子

先看一个Catagory.目的是增加UIButton的相应范围.

@implementation UIButton (TouchResponse)
- (void)touchResponseWithVector:(CGVector)vector {
    DLog(@"self.frame:%@",NSStringFromCGRect(self.frame));
    CGRect touchFrame = CGRectInset(self.frame, vector.dx, vector.dy);
    DLog(@"touchFrame:%@",NSStringFromCGRect(touchFrame));
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(-vector.dy, -vector.dx, -vector.dy, -vector.dx);
    self.imageEdgeInsets = edgeInsets;
    self.frame = touchFrame;
}
@end