UIButton默认有TitilLable 和 ImageView 组成。
默认现实风格:
但是有时候,我们想文字在左边,图标在右边。又有时候图片在上面文字在下面居中现实。
UIButton居中现实 UIButton文字左边代码:
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 150, 130)];
[button setImage:[UIImage imageNamed:@"dd_album"] forState:UIControlStateNormal];
[button setTitle:[NSString stringWithFormat:@"相册"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self.view addSubview:button];
button.titleLabel.backgroundColor = [UIColor greenColor];
button.layer.cornerRadius = 1;
button.layer.borderColor = [UIColor blackColor].CGColor;
button.layer.borderWidth = 1;
CGRect imageRect = button.imageView.frame;
CGRect titleRect = button.titleLabel.frame;
// 居中现实
// button.imageEdgeInsets = UIEdgeInsetsMake(-titleRect.size.height, titleRect.size.width, 0, 0);
// button.titleEdgeInsets = UIEdgeInsetsMake(imageRect.size.height, -imageRect.size.width, 0, 0);
// 文字在左边,图在右边
button.imageEdgeInsets = UIEdgeInsetsMake(0, titleRect.size.width, 0,-titleRect.size.width);
button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageRect.size.width, 0, imageRect.size.width);
UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)
设置的是分别和上边界,左边界,下边界,右边界的偏移量。
网友评论