发现一篇讲得有些原理的博客:
UIButton的titleEdgeInsets属性和imageEdgeInsets属性实现图片文字按要求排列
里面还有写好的category方法可以直接使用。
下面是图片右边,文字左边的一个按钮设置方法:
UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
[rightButton setTitle:@"这个是一个导航栏按钮" forState:UIControlStateNormal];
rightButton.titleLabel.font = SYSTEMFONT(14);
[rightButton setImage:[UIImage imageNamed:@"icon_filter"] forState:UIControlStateNormal];
[rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -rightButton.imageView.bounds.size.width, 0, rightButton.imageView.bounds.size.width)];
[rightButton setImageEdgeInsets:UIEdgeInsetsMake(0, rightButton.titleLabel.bounds.size.width, 0, -rightButton.titleLabel.bounds.size.width)];
[rightButton addTarget:self action:@selector(testFunction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];