【问题标题】:iOS Create Button with two separate labelsiOS 创建带有两个单独标签的按钮
【发布时间】:2014-05-29 19:52:13
【问题描述】:

我想创建一个带有两个独立标签的按钮。 我想在一个按钮中设置两个不同颜色的单独文本。 例如

[myButton setTitle: @"Title" forState: UIControlStateNormal]; 
[myButton setTitle2: @"Title2" forState: UIControlStateNormal]; 

有可能吗?也许我应该需要创建一个新控件?谁能帮我?我将非常感谢一步一步的教程。

【问题讨论】:

  • 抱歉回复晚了,还有我的英语。请原谅我可能对问题的描述不清楚。谢谢大家的帮助。

标签: ios uibutton


【解决方案1】:

如果您想在 Interface Builder 中完成所有操作,您可以在视图中您想要的位置放置两个 UILabel,然后在它们的顶部放置一个 UIButton。然后使用属性检查器将 UIButton 的类型更改为“自定义”并删除它拥有的任何现有标签或占位符文本。这将使按钮清晰,因此两个标签都显示出来,并且您可以将 UIButton 的 IBAction 设置为对两个单独的 UILabel 执行任何您想要的操作。

【讨论】:

  • 如果您这样做,请确保为按钮添加辅助功能标签以帮助视障人士,并帮助您编写 UI 测试。另外,不要忘记编写 UI 测试。
【解决方案2】:

另外,你可以这样做:

UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(0, 0, 200, 40);
[self.view addSubview:testButton];

UILabel *firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
firstLineTestButton.text = @"First line";
firstLineTestButton.font = [UIFont systemFontOfSize:12];
[testButton addSubview:firstLineTestButton];

UILabel *secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
secondLineTestButton.text = @"Second line";
secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[testButton addSubview:secondLineTestButton];

但@vikingosegundo 的解决方案更适合新的 SDK

【讨论】:

  • 谢谢。这正是我需要的。两个单独的标签。谢谢你的例子。 :-)
【解决方案3】:

对于 iOS 6 及更高版本,您可以使用 setAttributedTitle:forState: 设置属性字符串。一个 NSAttributedString 可以有很多不同的属性,比如文本颜色。

【讨论】:

  • 这将允许他将多种样式应用于单个按钮标签。它不允许他拥有多个独立的标签。当然,这个问题并不清楚他实际上想要完成什么。
【解决方案4】:

Swift 版本:

以下代码还在按钮内水平和垂直居中两个标题,并进行了一些字体样式调整。

let lineOne = UILabel.init(frame: CGRect(x: 0, y: self.button.frame.size.height / 4, width: self.button.frame.size.width, height: self.button.frame.size.height / 4))
lineOne.text = "Title 1"
lineOne.textColor = .black
lineOne.font = UIFont.boldSystemFont(ofSize: 13.0)
lineOne.textAlignment = .center
                
let lineTwo = UILabel.init(frame: CGRect(x: 0, y: lineOne.frame.size.height * 2, width: self.button.frame.size.width, height: self.button.frame.size.height / 4))
lineTwo.text = "Title 2"
lineTwo.textColor = .black
lineTwo.font = UIFont.boldSystemFont(ofSize: 13)
lineTwo.textAlignment = .center

self.button.addSubview(lineOne)
self.button.insertSubview(lineTwo, belowSubview: lineOne)

【讨论】:

    【解决方案5】:

    UIButtonUIView 的子类。因此,您可以使用- (void)addSubview:(UIView *)view 为您的按钮添加两个不同的标签。然后可以使用 Autolayout(如果您使用它)或框架 + 弹簧/支柱来完成定位。

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多