原文地址: http://blog.csdn.net/qq_31810357/article/details/78364336
文章说明: 未经授权严禁转发套作;
iOS11出来以后导航栏自定义按钮会出现偏移问题,如下图:
解决方案: 1.修改偏移量; 2.调整响应范围;
我的导航栏是storyboard 拖UIButton进去的, 所以我在控制器下拖拉了属性:
1.解决偏移问题:
// 我的设备
[letButton setImage:[UIImage imageNamed:@"health_leftBtn"] forState:UIControlStateNormal];
[letButton setTitle:@"我的设备" forState:UIControlStateNormal];
letButton.titleLabel.font = [UIFont systemFontOfSize:10.0];
[letButton JQ_verticalCenterImageAndTitle:0];
letButton.contentEdgeInsets = UIEdgeInsetsMake(0, -40,0, 0);
letButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20,0, 0);
[letButton JQ_verticalCenterImageAndTitle:3];
2.解决响应事件的触发范围:
// 解决扩大响应范围
[letButton setEnlargeEdgeWithTop:0 right:10 bottom:10 left:40];
其中解决触发范围使用了Runtime,代码如下:
// .h
#import
@interface UIButton (EnlargeTouchArea)
- (void)setEnlargeEdgeWithTop:(CGFloat)top right:(CGFloat)right bottom:(CGFloat)bottom left:(CGFloat)left;
@end
// .m
#import "UIButton+EnlargeTouchArea.h"
#import
@implementation UIButton (EnlargeTouchArea)
static char topNameKey;
static char rightNameKey;
static char bottomNameKey;
static char leftNameKey;
- (void)setEnlargeEdgeWithTop:(CGFloat)top right:(CGFloat)right bottom:(CGFloat)bottom left:(CGFloat)left
{
objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (CGRect)enlargedRect
{
NSNumber *topEdge = objc_getAssociatedObject(self, &topNameKey);
NSNumber *rightEdge = objc_getAssociatedObject(self, &rightNameKey);
NSNumber *bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);
NSNumber *leftEdge = objc_getAssociatedObject(self, &leftNameKey);
if (topEdge && rightEdge && bottomEdge && leftEdge)
{
return CGRectMake(self.bounds.origin.x - leftEdge.floatValue,
self.bounds.origin.y - topEdge.floatValue,
self.bounds.size.width + leftEdge.floatValue + rightEdge.floatValue,
self.bounds.size.height + topEdge.floatValue + bottomEdge.floatValue);
} else {
return self.bounds;
}
}
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
CGRect rect = [self enlargedRect];
if (CGRectEqualToRect(rect, self.bounds)) {
return [super hitTest:point withEvent:event];
}
return CGRectContainsPoint(rect, point) ? self : nil;
}
@end