我添加了一个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的控件。我怎样才能做到这一点?

最佳答案

子类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!
}

09-29 21:04