iOS11导航栏按钮偏移问题

原文
iOS11 完美解决导航栏按钮偏移问题

iOS11出来以后导航栏自定义按钮会出现偏移问题

解决方案: 1.修改偏移量; 2.调整响应范围;

1.解决偏移问题:

// 我的设备
[letButton setImage:[UIImage imageNamed:@"health_leftBtn"] forState:UIControlStateNormal];
[letButton setTitle:@"我的设备" forState:UIControlStateNormal];
letButton.titleLabel.font = [UIFont systemFontOfSize:10.0];

letButton.contentEdgeInsets = UIEdgeInsetsMake(0, -40,0, 0);
letButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20,0, 0);

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

iOS开发者交流群(官方收费群):①446310206 ②446310206

推荐资源:

iOS-Swift-Developers

iOS-OC-Developer

你可能感兴趣的:(iOS11导航栏按钮偏移问题)