突然发现自定义完 leftBarButtonItem 然后自定义titleView,titleView往右偏移
究其原因是因为 设置titleview之前,先初始化leftBarButtonItem和rightBarButtonItem的位置,然后根据leftBarButtonItem和rightBarButtonItem的位置来使titleview居中。
//必须放在 leftBarButtonItem和rightBarButtonItem初始化之后调用
废话不说 上代码
CGRect leftViewbounds = self.navigationItem.leftBarButtonItem.customView.bounds;
CGRect rightViewbounds = self.navigationItem.rightBarButtonItem.customView.bounds;
CGRect frame;
CGFloat maxWidth = leftViewbounds.size.width > rightViewbounds.size.width ? leftViewbounds.size.width : rightViewbounds.size.width;
maxWidth += 15;//leftview 左右都有间隙,左边是5像素,右边是8像素,加2个像素的阀值 5 + 8 + 2
frame = self.titleLabel.frame;
frame.size.width = SWIDTH - maxWidth * 2;
self.titleLabel.frame = frame;
self.navigationItem.titleView = self.titleLabel;
网友评论