【问题标题】:Set title for UIButton that has an image为具有图像的 UIButton 设置标题
【发布时间】:2015-04-22 09:35:29
【问题描述】:

我无法使用标准 [button setTitle:@"Title"..] 为我的 UIButton 设置标题 我现在将UILabel 放在UIButton 的顶部,但我无法让标签在auto-layout 中完美对齐。
注意:我有一张图片UIButton

【问题讨论】:

  • 从右侧的下拉选项卡中选择捆绑包中的图像

标签: ios xcode uibutton autolayout


【解决方案1】:

设置按钮背景图片并将标题设置为按钮

[button setBackgroundImage:[UIImage imageNamed:@"yourButtonImageName"] forState:UIControlStateNormal];
[button setTitle:@"Title" forState:UIControlStateNormal];
[button.titleLabel setNumberOfLines:0];

【讨论】:

    【解决方案2】:

    将图像设置为按钮的背景。那么标题应该是可见的。

    如果还需要在 Button 上放置 Label,可以在代码中添加 Auto Layout 约束。他们在这种情况下工作。

    编辑:在 Playground 中使用的 Swift 示例:

    import UIKit
    import XCPlayground
    
    let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
    
    hostView.layer.borderWidth = 1
    hostView.layer.borderColor = UIColor.grayColor().CGColor
    
    let button = UIButton.buttonWithType(.Custom) as! UIButton
    button.backgroundColor = UIColor.redColor()
    
    hostView.addSubview(button)
    button.setTranslatesAutoresizingMaskIntoConstraints(false)
    button.setTitle("This is a really long title for this button", forState: .Normal)
    button.titleLabel!.numberOfLines = 0
    
    NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-50-[button(100)]", options: nil, metrics: nil, views: ["button": button]))
    NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[button(100)]", options: nil, metrics: nil, views: ["button": button]))
    
    XCPShowView("Host View", hostView)
    

    【讨论】:

    • 这行得通..但是我需要对此进行更新..我的意思是,我可以增加标题的行数吗,就像我可以在 UILabel 中设置一样,这样内容就不会消失超出按钮的边界?
    • 设置按钮textLabel的numberOfLines属性为0,使按钮足够大。
    【解决方案3】:

    您可以使用带有标题和图像的 UIButton,但您必须注意图像和标题edgeInset 例如[btn setTitleEdgeInsets:UIEdgeInsetsMake(70.0, -150.0, 5.0, 5.0)];

    详情请见answer

    【讨论】:

      【解决方案4】:

      在这种情况下,我建议创建您自己的自定义视图。 创建一个视图并包含一个标签和一个 uiimageview 作为子视图

      根视图:
      ++++++++++++++
      UIImageView
      ----------------------
      UILabel
      ++++++++++++++

      然后你可以在 rootview 中添加 tapgesture 来模拟按钮的行为。

      【讨论】:

      • 在这种情况下重新创建 UIButton 似乎有点过头了。
      猜你喜欢
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 2012-09-28
      • 1970-01-01
      相关资源
      最近更新 更多