【问题标题】:How to show the title under the UIButton?如何在 UIButton 下显示标题?
【发布时间】:2023-03-25 10:27:01
【问题描述】:
我已使用标题插图在UIButton 下显示文本名称。
这是我的代码和输出:
[button setTitleEdgeInsets:UIEdgeInsetsMake(60, 0, 0, 0)];
这是我的预期输出:
我使用了UIButton 并将标题和UIImage 设置为背景。那么如何在UIButton下显示标题标签呢?
【问题讨论】:
标签:
ios
objective-c
uibutton
uiimage
【解决方案1】:
您尝试做的是正确的;您只需要设置插入边缘,如下所示。然后你需要增加你的按钮框架,以便它可以同时容纳标题和图像。
[button setTitleEdgeInsets:UIEdgeInsetsMake(60, 0, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0.0f, 0.f, button.titleLabel.frame.size.height, 0.f)];
这也可以通过故事板来完成,正如@VD Patel 建议的那样,这取决于您喜欢哪种方法。
您也可以使用单独的UIImageview 和一个更易于处理且效率更高的按钮来执行此操作。
【解决方案2】:
请先在 xib 中选择按钮。然后选择 Attribute Inspector,在此 Select Title in "Edge" 中并根据要求设置适当的 "Inset"。
请查看以下代码并根据您的要求设置插图。
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0, 0, self.view.bounds.size.width, 40);
[myButton setImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
[myButton setTitle:@"Rate us on app store" forState:UIControlStateNormal];
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(2, 50, 2, 20)];//set ur title insects myButton
[myButton setImageEdgeInsets:UIEdgeInsetsMake(2, -200, 2, 2)];//make negative edge for left side
[myButton setBackgroundColor:[UIColor greenColor]];
[self.view myButton];
【解决方案3】:
创建UIImageView、UILabel 和UIButton。稍后将 ImageView 和 Label 作为子视图添加到 Button。
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 200, 100)];
lbl.textAlignment = NSTextAlignmentCenter;
[lbl setText:@"Mono"];
UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
imgView.image = [UIImage imageNamed:@"your_image.png"];
[imgView setUserInteractionEnabled:NO];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addSubview:imgView];
[btn addSubview:lbl];
[btn setFrame:CGRectMake(0, 20, 200, 300)];
[btn addTarget:self action:@selector(OnButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
尝试在 viewDidLoad 方法中添加此代码。