如果按照系统自带的方法写没有问题,代码如下:
UIBarButtonItem* leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"default"]
imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style: UIBarButtonItemStylePlaintarget:self action:@selector(leftItemAction)];
self.navigationItem.leftBarButtonItem= leftItem;
但是显示的图片是用户的头像,是一个随时可能修改的url链接,这时候系统自带的方法就无法满足了,
必须使用自定义,代码如下:
//_personalBtn为当前控制器属性值,因为用户修改图像的时候需要刷新(需要用到第三方库SDWebImage)
_personalBtn= [UIButtonbuttonWithType:UIButtonTypeCustom];
_personalBtn.frame=CGRectMake(0,0,40,40);
[_personalBtn sd_setImageWithURL:[NSURL URLWithString:_model.headUrl]
forState:UIControlStateNormal placeholderImage:[UIImageimageNamed:@"ev_circle_default"]];
_personalBtn.layer.masksToBounds=YES;
_personalBtn.layer.cornerRadius=40/2;
[_personalBtn addTarget:selfaction:@selector(leftItemAction) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* leftItem = [[UIBarButtonItem alloc] initWithCustomView:_personalBtn];
self.navigationItem.leftBarButtonItem= leftItem;
显示如下:
现在显示正常,可能因为有这句代码_personalBtn.frame=CGRectMake(0,0,40,40);
当你跳转其它页面在返回回来的时候就显示如下了:
连标题都不见了,是不是很奇葩,换成UIImageView也是如此。
解决代码:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,40,40)];
view.backgroundColor = [UIColor clearColor];
_personalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_personalBtn.frame = CGRectMake(0, 0, 40, 40);
[_personalBtn sd_setImageWithURL:[NSURL URLWithString:_model.headUrl] forState:UIControlStateNormal
placeholderImage:[UIImage imageNamed:@"ev_circle_default"]];
_personalBtn.layer.masksToBounds = YES;
_personalBtn.layer.cornerRadius = 40/2;
[_personalBtn addTarget:self action:@selector(leftItemAction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:_personalBtn];
UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:view];
self.navigationItem.leftBarButtonItem= leftItem;
至于为什么解决了,我也想不明白,可能是view的大小限制了btn的大小,谢谢浏览,如果你找到了这其中的原因,求赐教