UIButton和UINavigationItem设置图片和文字位置

时间:2022-11-13 17:35:45

1.UIButton设置文字位置

有些时候我们想让UIButton的title居左对齐,我们设置

btn.textLabel.textAlignment = UITextAlignmentLeft

是没有作用的,我们需要设置

btn.contentHorizontalAlignment = UIControlContentHorizonAlignmentLeft;

但是问题又出来,此时文字会紧贴到做边框,我们可以设置

btn.contentEdgeInsets = UIEdgeInsetsMake(,, , );//使文字距离做边框保持10个像素的距离。

如果是图片+文字:


UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = buttonRect;
[button setTitle:@"title" forState:UIControlStateNormal];
[button setImage:buttonImage forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(0.0, WIDTH(button.titleLabel) + 10.0, 0.0, 0.0);

2.自定义UINavigationItem包含图片和文字

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];  

// 设置frame只能控制按钮的大小
btn.frame= CGRectMake(, , , ); [btn addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:btn]; UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; /** * width为负数时,相当于btn向右移动width数值个像素,由于按钮本身和边界间距为5pix,所以width设为-5时,间距正好调整 * 为0;width为正数时,正好相反,相当于往左移动width数值个像素 */ negativeSpacer.width = -; self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];