[英]Increase tap area of UIBarButtonitem to the left far side of navigation bar
我使用以下代碼將后退按鈕欄項添加到導航欄。
CGSize size = CGSizeMake(40, 40);
UIImage *image = [mysdk.icon.backArrow make];
UIButton *back = [self.class buttonForBarItemByImage:image size:size];
back.backgroundColor = [UIColor grayColor];
UIBarButtonItem *backArrow = [[UIBarButtonItem alloc] initWithCustomView:back];
[back addTarget:backArrow action:@selector(backArrow_onClick) forControlEvents:UIControlEventTouchUpInside];
+ (UIButton *) buttonForBarItemByImage:(UIImage *)image size:(CGSize)size {
UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
[back setImage:image forState:UIControlStateNormal];
CGSize buttonSize = size;
back.frame = CGRectMake(0, 0, buttonSize.width, buttonSize.height);
return back;
}
如下圖所示,按鈕已添加。 按鈕的圖像位於灰色區域的中間。 灰色區域是點擊區域。
如您所見,我用紅色圈出仍然是黃色的區域。 所以我需要讓這個區域可以點擊。 按鈕圖像不應該移動,只是從左側增加點擊區域。 這有可能嗎?
您可以使用子類UINavigationBar
做到這一點:
我的導航欄
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyNavBar : UINavigationBar
@end
NS_ASSUME_NONNULL_END
我的導航欄.m
#import "MyNavBar.h"
@implementation MyNavBar
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
// get the custom view (the UIButton)
UIView *v = self.topItem.leftBarButtonItem.customView;
if (v) {
// convert the button's frame to its superview coordinate space
CGRect r = [self convertRect:v.frame toView:v.superview];
// convert the point to the button's coordinate space
CGPoint p = [self convertPoint:point toView:v];
// if p is inside r
if (CGRectContainsPoint(r, p)) {
// return the custom view
return v;
}
}
return [super hitTest:point withEvent:event];
}
@end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.