【问题标题】:How to call method of all custom UIView in a ViewController?如何在 ViewController 中调用所有自定义 UIView 的方法?
【发布时间】:2016-03-22 18:54:10
【问题描述】:

我创建了一个自定义 UIView,里面有一个 UIButton 当我点击它时,它会简单地改变它的背景颜色。

我想知道如何在此自定义 UIView 的所有实例中更改此按钮的背景颜色。

有什么想法吗?

import UIKit

class RadioChannelView: UIView {

    var playButton:UIButton!

    init(frame: CGRect, themeColor: UIColor) {
        super.init(frame: frame)

        playButton = UIButton(type: .Custom)
        playButton.backgroundColor = UIColor.blackColor()
        playButton.layer.cornerRadius = 40

        playButton.addTarget(self, action: "playButtonTapped", forControlEvents: .TouchUpInside)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func playButtonTapped() {
        self.playButton.backgroundColor = UIColor.redColor()
    }

}

【问题讨论】:

  • 您必须遍历所有子视图并更改该按钮的背景颜色。
  • 你可以做UIButton.appearanceWhenContainedInInstancesOfClasses([RadioChannelView.self]).backgroundColor = UIColor.redColor()

标签: ios swift uiview uibutton


【解决方案1】:

其中一种方法是将您的RadioChannelView 类作为观察者添加到NSNotificationCenter。单击按钮时,将您的通知发布给观察者,然后它会唤醒此通知的侦听器方法,您可以在其中更改背景。

class RadioChannelView: UIView {

    var playButton:UIButton!

    init(frame: CGRect, themeColor: UIColor) {
        super.init(frame: frame)

        playButton = UIButton(type: .Custom)
        playButton.backgroundColor = UIColor.blackColor()
        playButton.layer.cornerRadius = 40

        playButton.addTarget(self, action: "playButtonTapped", forControlEvents: .TouchUpInside)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveBtnClickNotification:", name: "button_clicked", object: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func playButtonTapped() {
        NSNotificationCenter.defaultCenter().postNotificationName("button_clicked", object: nil);
    }

    func didReceiveBtnClickNotification(sender: NSNotification!) {
        self.playButton.backgroundColor = UIColor.redColor()
    }
}

【讨论】:

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