【问题标题】:Can't change attributes of button in view loaded from nib file无法更改从 nib 文件加载的视图中按钮的属性
【发布时间】:2017-10-24 17:26:56
【问题描述】:

我正在加载我在界面构建器中创建的视图,如下所示:

let contentView = Bundle.main.loadNibnamed("ContentView", owner: nil, options: nil)?.first as! ContentView

视图包含一个 UIImageView 和一个 UIButton。它们都通过 IBOutlets 连接到 ContentView 类文件。

现在,当我加载视图时,我正在设置 UIImageView 的图像,它工作正常。我也在尝试更改 UIButton 的文本和背景颜色,但两者都不会改变。有趣的是,按钮并没有保留我在界面生成器中设置的颜色,而是保留了文本。

我用来更改文本和颜色的代码:

contentView.contentButton.backgroundColor = .red
contentView.contentButton.titleLabel?.text = "someText"

感谢您的帮助。

ContentView.swift
class ContentView: UIView {
   @IBOutlet weak var mainImageView: UIImageView!
   @IBOutlet weak var contentImageView: UIImageView!
   @IBOutlet weak var contentButton: UIButton! 
}

我用来创建视图的代码:

ContentScrollViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0..<imageArray.count {
        let xPosition = Int(self.view.frame.width) * i

        let contentView: ContentView = Bundle.main.loadNibNamed("ContentView", owner: nil, options: nil)?.first as! ContentView

        contentView.frame.origin = CGPoint(x: xPosition, y: -Int((self.navigationController?.navigationBar.frame.height)!))

        contentView.mainImageView.contentMode = .scaleAspectFill
        contentView.contentImageView.image = #imageLiteral(resourceName: "stoerer_png_neu")

        //Not working 
        contentView.specialButton.backgroundColor = .red

        if let url = URL(string: imageArray[i]) {
            contentView.mainImageView.af_setImage(withURL: url)
        }

        mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)

        mainScrollView.addSubview(contentView)
    }

}

【问题讨论】:

  • 我假设ContentViewUIView 的子类?如果是,是设置为XIB的FIle's Owner还是设置为XIB中视图的自定义类?
  • 是的 ContentView 是 UIView 的子类,在 .xib 中设置为视图的自定义类。
  • 您可能需要仔细检查所有 IBOutlet 连接,或者从头开始重新启动您的 ContentView。我正在关注您的代码以及您设置 IBOutlets 的方式,我没有遇到任何问题。

标签: ios uiimageview uibutton xib nib


【解决方案1】:

你必须使用

contentView.contentButton.setTitle("someText", for: .normal)

contentView.contentButton.setTitleColor(.red, for: .normal)

因为您需要为特定的 UIControlState 设置这些属性

对于你需要使用图层的背景:

contentView.contentButton.layer.backgroundColor = UIColor.red.cgColor

【讨论】:

  • 设置文本的解决方案有效,但第二个仅更改 titleColor 而不是 UIButtons backgroundColor。
  • 遗憾地将图层 backgroundColor 设置为 cgColor 对我不起作用。
  • contentView.contentButton.layer.backgroundColor = UIColor.red.cgColor 或者你还需要什么?
  • @Maci 你使用 backgroundImage 还是别的什么?因为这将正常工作,我在 10 分钟前进行了测试。是有错误还是只是不起作用?
  • 不,我没有为按钮使用 backgroundImage。
【解决方案2】:

重新启动所有与问题相关的文件后,我终于找到了问题所在。不知何故,.xib 中的 UIButton 的约束是导致该问题的原因。因此,如果您遇到相同的情况,请检查您的限制。 :]

【讨论】:

    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多