繁体   English   中英

如何在 UIButton 下显示标题?

[英]How to show the title under the UIButton?

我使用标题插图在UIButton下显示文本名称。

这是我的代码和输出:

 [button setTitleEdgeInsets:UIEdgeInsetsMake(60, 0, 0, 0)];

在此处输入图片说明

这是我的预期输出:

在此处输入图片说明

我使用了UIButton并将标题和UIImage设置为背景。 那么如何在UIButton下显示标题标签呢?

你试图做的是正确的; 你只需要按照下面的方法设置插入边缘。 然后你需要增加你的按钮框架,以便它可以同时容纳标题和图像。

[button setTitleEdgeInsets:UIEdgeInsetsMake(60, 0, 0, 0)];

[button setImageEdgeInsets:UIEdgeInsetsMake(0.0f, 0.f, button.titleLabel.frame.size.height, 0.f)];

这也可以通过故事板来完成,因为@VD Patel 建议这取决于您喜欢哪种方法。

您还可以使用单独的UIImageview和一个更易于处理且效率更高的按钮来执行此操作。

请先在xib中选择按钮。 然后选择属性检查器,在“Edge”中的这个 Select Title 中,并根据要求设置适当的“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];

创建UIImageViewUILabelUIButton 然后将 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 方法中添加此代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM