详解button设置文字和图片

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.backgroundColor = kRandomColor;

button.tag = i + addTag;

button.frame = CGRectMake(kScreenWidth / 3 * i, 0, kScreenWidth / 3, 50);

//首先设置需要显示的文字和图片

[button setTitle:titleArray[i] forState:UIControlStateNormal];

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[button setImage:image forState:UIControlStateNormal];

//再将文字和图片进行偏移处理

//这里+3和-3是需要文字和图片有一定的间隔

[button setTitleEdgeInsets:UIEdgeInsetsMake(0, -image.size.width, 0, image.size.width)];

[button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width+3, 0, -button.titleLabel.bounds.size.width-3)];

//自己去将图片进行修改

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{

// 创建一个bitmap的context

// 并把它设置成为当前正在使用的context

UIGraphicsBeginImageContext(size);

// 绘制改变大小的图片

[img drawInRect:CGRectMake(0, 0, size.width, size.height)];

// 从当前context中创建一个改变大小后的图片

UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

// 使当前的context出堆栈

UIGraphicsEndImageContext();

// 返回新的改变大小后的图片

return scaledImage;

}

你可能感兴趣的:(详解button设置文字和图片)