访问UIButton的子视图控件

时间:2015-03-05 13:24:30

标签: ios swift uibutton uilabel subview

我添加了一个UILabel作为UIButton的子视图

var actLabel = UILabel(frame: CGRectMake(35, 0, 90, favHeight)) actLabel.font = UIFont(name: "Helvetica", size: 14) actLabel.text = "Actions" actLabel.textColor = darkBlueColor actLabel.textAlignment = NSTextAlignment.Center actPanel.addSubview(actLabel) 其中actPanel是UIButton

关于这个UIButton的动作,我想访问这个UILabel的控件。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

子类UIButton

class ActionButton : UIButton {
    var actionLabel: UILabel!
}

var actLabel = UILabel(frame: CGRectMake(35, 0, 90, favHeight))
actLabel.font = UIFont(name: "Helvetica", size: 14)
actLabel.text = "Actions"
actLabel.textColor = darkBlueColor
actLabel.textAlignment = NSTextAlignment.Center
actPanel.addSubview(actLabel)
actPanel.actionLabel = actLabel

或者将智慧融入课堂

class ActionButton : UIButton {
    var favoriteHeight: CGFloat = 80 // Or whatever default you want.
    var darkBlueColor: UIColor = UIColor(red: 0, green: 0, blue: 0.75, alpha: 1) // Or whatever

    @IBOutlet var actionLabel: UILabel! {
        get {
            if _actionLabel == nil {
                var actLabel = UILabel(frame: CGRectMake(35, 0, 90, favoriteHeight))
                actLabel.font = UIFont(name: "Helvetica", size: 14)
                actLabel.textColor = darkBlueColor
                actLabel.textAlignment = NSTextAlignment.Center
                addSubview(actLabel)

                _actionLabel = actLabel
            }
            return _actionLabel
        }
        set {
            _actionLabel?.removeFromSuperview()
            _actionLabel = newValue
            if let label = _actionLabel {
                addSubview(label)
            }
        }
    }

    override func willMoveToSuperview(newSuperview: UIView?) {
        // Ensure actionLabel exists and the text has a value.
        if actionLabel.text == nil || actionLabel.text!.isEmpty {
            actionLabel.text = "Action" // Provide a default value
        }
    }

    private var _actionLabel: UILabel!
}

答案 1 :(得分:0)

您可以通过

访问所有子视图
var subviews = actPanel.subviews()

然后你可以遍历那个数组并找到你的标签。

但如果您将此标签作为按钮的标题,则UIButton已经拥有自己的titleLabel。

答案 2 :(得分:0)

如果您为actPanel创建了一个类并将标签添加为属性,则可以使用actPanel.actLabel.text = "Actions"访问它,否则您可以像以前一样访问它:actLabel.text = "Actions"