如何在UIButton下显示标题?

时间:2015-05-19 10:30:46

标签: ios objective-c uibutton uiimage

我使用标题inset在UIButton下显示文字名称。

这是我的代码和输出:

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

enter image description here

这是我的预期输出:

enter image description here

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

有人可以提供建议吗?

3 个答案:

答案 0 :(得分:3)

你要做的是正确的;你只需要设置插入边缘,如下所示。然后你需要增加你的按钮框架,以便它可以同时保存标题和图像。

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

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

这也可以通过故事板来完成,因为@VD Patel建议您选择哪种方式。

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

答案 1 :(得分:1)

请先选择xib中的按钮。然后选择属性检查器,在“边缘”中选择标题,并根据要求设置适当的“插入”。

请查看以下代码并根据您的要求设置插入内容。

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];

答案 2 :(得分:0)

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