问题
I was trying to create a custom button, but after setting the image, I noticed that the title disappears, it think this is because I add an image to the button, which overlaps the title.
UIImage *pickerBg = [UIImage imageNamed:@"btn_picker.png"];
UIImage *pickerBg_highlighted = [UIImage imageNamed:@"btn_picker_highlighted.png"];
[projectBtn setImage:pickerBg forState:UIControlStateNormal];
[projectBtn setImage:pickerBg_highlighted forState:UIControlStateHighlighted];
Is there another way on how to do this?
回答1:
Create a UILabel with the title you need, then add it as a subview to your UIButton.
回答2:
Use setBackgroundImage, not setImage
回答3:
UIImage *pickerBg = [UIImage imageNamed:@"btn_picker.png"];
UIImage *pickerBg_highlighted = [UIImage imageNamed:@"btn_picker_highlighted.png"];
[projectBtn setBackgroundImage:pickerBg forState:UIControlStateNormal];
[projectBtn setBackgroundImage:pickerBg_highlighted forState:UIControlStateHighlighted];
[projectBtn setTitle:@"aTitle" forState:UIControlStateNormal];
Use this to set image with title.
回答4:
when you create a UIButton, use setImage to set ButtonImage will change title's position,the titleText and the image are at At the same level,the titleText in behind of image,so you can setBackImage, the image will behind the titleText,but ,the image will tension as the button.
来源:https://stackoverflow.com/questions/10597271/uibutton-with-custom-background-loses-title