【问题标题】:Swift: Set properties to an Extension of IBOutletCollection containing UIButtonsSwift:将属性设置为包含 UIButtons 的 IBOutletCollection 的扩展
【发布时间】:2019-05-19 01:42:37
【问题描述】:

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

虽然有类似的问题:

1.Change the color of UIButton in IBOutletCollection

2.Set Individual Title of UIButtons in IBOutletCollection

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

这是我目前收集到的:

  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()

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

谢谢。

【问题讨论】:

    标签: uibutton nsarray iboutletcollection


    【解决方案1】:

    经过这么多的反复试验,我终于找到了解决方案。我想与需要在 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”。我希望这能让感觉!

    再见!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      相关资源
      最近更新 更多