Adi*_*tya 115
您可以使用此代码,它将满足您的目的
.h file code
IBOutlet UIButton *testBtn;
.m file code
[testBtn setImage: [UIImage imageNamed:@"Image name.png"] forState:UIControlStateNormal];
[testBtn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];
[testBtn setTitle:@"Your text" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
根据您的要求调整按钮的坐标和大小.这是一个示例代码,可以指导您.
PS:在nib文件中取一个UIButton>将其设为自定义按钮>将IBOutlet连接到nib文件中的自定义按钮.对此进行说明.
小智 14
下面的代码显示了使用UIButton类的setImageEdgeInsets和setTitleEdgeInsets属性将图像和文本放在按钮中.
UIButton *butt=[UIButton buttonWithType:UIButtonTypeCustom ];
[butt setFrame:CGRectMake(0, 0, 100, 100)];
[butt setBackgroundImage:[UIImage imageNamed:@"sig.png"] forState:UIControlStateNormal];
[butt setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 50.0, 0.0)];
[butt setTitleEdgeInsets:UIEdgeInsetsMake(75.0, 0.0, 0.0, 0.0)];
[butt setTitle:@"hello" forState:UIControlStateNormal];
[butt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:butt];
Run Code Online (Sandbox Code Playgroud)
使用子视图的概念.取3个控件,UIButton(200x270),UILabel(200x120)和UIImageView(200x150).将图像分配给UIImageView并设置文本UILabel.根据标签的(x,y)位置定位标签和图像视图控件UIButton.
最后,你应该有类似的东西:
对于以下实例:
UIButton *button;
UILabel *label;
UIImageView *imageView;
[button addSubView:imageView];
[button addSubView:label];
Run Code Online (Sandbox Code Playgroud)
在斯威夫特 3
let button = UIButton()
//make sure the image (jpg, png) you are placing in the button
//is about the right size or it will push the label off the button
//add image
let image = UIImage(named:"my_button_image")
button.setImage(image, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top:0, left:-30, bottom:0, right:0) //adjust these to have fit right
//add title
button.setTitle("Fan", for: .normal)
button.titleEdgeInsets = UIEdgeInsets(top:0, left:10, bottom:0, right:0) //adjust insets to have fit how you want
//add button to your view - like in viewDidLoad or your own custom view setup
addSubview(button)
Run Code Online (Sandbox Code Playgroud)
如果以编程方式设置锚点,请不要忘记设置锚点,以便在使用故事板时将其显示/附加到界面生成器中的按钮引用
[testBtn setBackgroudImage: [UIImage imageNamed:@"Image name.png"] forState:UIControlStateNormal];
[testBtn setTitle:@"Your text" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
是的,只要它们都足够小,就可以在同一按钮中显示图像和标题。当您需要处理展示位置时,困难的部分就来了。
您可以使用(继承自)的contentVerticalAlignment和contentHorizontalAlignment属性。UIButtonUIControl
您还可以使用titleEdgeInsets和imageEdgeInsets属性,根据对齐方式将标题和图像从它们获得的位置移开。
如果您想要非常准确或自定义的展示位置,建议您覆盖的titleRectForContentRect:和imageRectForContentRect:方法UIButton。这些允许您定义标题和图像的框架,并在需要布置按钮时调用它们。一个警告,如果你想引用self.titleLabel里面titleRectForContentRect:,一定self.currentTitle首先被定义。我遇到了严重的访问错误,可能是在首次初始化titleLabel时调用了该方法。
| 归档时间: |
|
| 查看次数: |
80715 次 |
| 最近记录: |