0

如何将属性设置为包含“UIButtons”的“IBOutletCollection”的“扩展”?我正在尝试以与扩展 UIButton 类似的方式来执行此操作,这似乎并未扩展到 UIButton 的集合。我希望尽可能彻底和清晰。

虽然有类似的问题:

1.更改IBOutletCollection中UIButton的颜色

2.在IBOutletCollection中设置UIButtons的单独标题

...以及其他许多人。我仍然没有掌握如何做到这一点,并且可以真正使用你们任何人都可以提供的帮助。

这是我到目前为止收集的内容:

  1. IBOutletCollection 始终是 NSArray。
  2. 使用 for-in-loop 遍历数组的内容。

这是我的代码示例:(我尝试用类似于“Array”的“Collection”替换“Array”所在的位置:“NSArray”和“Collection”)

//Inside the main viewController:

@IBOutlet var ButtonCollection: [UIButton]!
//Inside the extention file:

extension Array where Element == UIButton
{
    func sharedButtonProperties()
    {
        for button in ButtonCollection
        {
            self.setTitleColor(.red, for: .normal)
           //MARK: More properties will go here, once I get this to work. 
        }
    }
}
//calling the code inside main viewController, within "viewDidAppear"

ButtonCollection.sharedButtonProperties()

现在这是一个 UIButton 的单个 IBOutlet 的扩展示例,它工作得很好,但不适用于 Collection:

//Inside the main viewController:

@IBOutlet weak var ButtonSingle: UIButton?
//Inside the extention file:

extension UIButton
{
    func buttonProperties()
        {
            self.setTitleColor(.red, for: .normal)
        }
}
//calling the code inside main viewController, within "viewDidAppear"

ButtonSingle?.buttonProperties()

我肯定不是专家编码器,非常感谢提供的任何帮助。

谢谢你。

4

1 回答 1

0

经过这么多的反复试验,我终于找到了解决方案。我想与任何需要在IBOutletCollection中为UIButtons设置属性的人分享答案。当您想为一组按钮或项目范围内的所有按钮设置/定义属性时,这是一种非常有效的方法来减少时间。

我真的希望有人觉得这很有用!

代码(测试和工作):请注意,粗体字是我所讨论的代码的变化。

//Inside the main viewController

@IBOutlet var ButtonCollection: [UIButton]!
//Inside the extention file:

extension Array where Element == UIButton
{
    func sharedButtonProperties()
    {
        for **buttonGrp** in **self**
        {
            **buttonGrp**.setTitleColor(.red, for: .normal)
           //MARK: More properties will go here now! 
        }
    }
}
//calling the code inside main viewController, within "viewDidAppear"

ButtonCollection.sharedButtonProperties()

正如你所看到的:我几乎想通了,但只需要为“for-in-loop”调用“buttonGrp”,并将其设置为“self”。我希望这有意义!

再见!

于 2019-05-20T03:42:18.503 回答