【问题标题】:UIButton's UILabel's background view does not adopt passed background colorUIButton UILabel 背景视图不采用传递的背景颜色
【发布时间】:2024-03-08 16:20:02
【问题描述】:

我正在尝试为以编程方式创建的 UIButton 着色:

    let button = UIButton( type: UIButtonType.System ) as UIButton
    button.frame = CGRectMake( 100, 100, 200, 50 )
    button.setTitleColor( MyColours.ORANGE, forState: .Normal )
    button.setTitle( "Some Button", forState: UIControlState.Normal )

    let backgroundColour =  UIColor.blueColor()
    button.backgroundColor = backgroundColour
    button.titleLabel?.backgroundColor = backgroundColour

    myView.addSubview( button )

但是,正如您从这张图片中看到的那样,按钮的标签有[我假设是]它自己的背景视图,它没有被着色。请问我做错了什么?

【问题讨论】:

  • 你的假设是错误的。按钮标题标签背景颜色正确设置为蓝色。我只在寻找按钮的白色边框
  • 你给按钮设置边框了吗?
  • 嗨巴拉吉。我不太明白你的意思,恐怕。为清楚起见:白色圆角区域之外的整个蓝色矩形区域是按钮。
  • 哦.. 好吧,我以为是你添加按钮的视图
  • 如果您从代码中删除 button.titleLabel?.backgroundColor = backgroundColour 行。结果如何?

标签: ios iphone swift uibutton uilabel


【解决方案1】:

您可以删除按钮的边框 button.layer.borderWidth = 0.0;

【讨论】:

  • 嗨,Martijn。我尝试了button.layer.borderWidth = 0.0;button.titleLabel?.layer.borderWidth = 0.0;,但都没有帮助。不过谢谢。
【解决方案2】:

重新排序代码已经消除了问题,这很好,虽然我不知道它是如何工作的或为什么工作,这不太好:

    var backgroundColour = UIColor.BlueColor()
    var foregroundColour = MyColours.ORANGE
    var button = UIButton( type: UIButtonType.System ) as UIButton

    button.frame = CGRectMake( 100, 100, 200, 50 )
    button.backgroundColor = backgroundColour
    button.setTitleColor( foregroundColour, forState: .Normal )
    button.setTitle( "Some Button", forState: UIControlState.Normal )

    myView.addSubview( button )

【讨论】: