访问 UIButton 的子视图控件
Posted
技术标签:
【中文标题】访问 UIButton 的子视图控件【英文标题】:Access subview controls of a UIButton 【发布时间】:2015-03-05 13:24:29 【问题描述】:我添加了一个 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 的控件。我该怎么做?
【问题讨论】:
【参考方案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!
【讨论】:
【参考方案2】:您可以通过
访问所有子视图var subviews = actPanel.subviews()
然后您可以遍历该数组并找到您的标签。
但是如果你有这个标签作为按钮的标题,那么 UIButton 已经有它自己的 titleLabel。
【讨论】:
【参考方案3】:如果您为 actPanel 创建了一个类并将标签添加为属性,您可以使用 actPanel.actLabel.text = "Actions"
访问它,否则您可以像以前一样访问它:actLabel.text = "Actions"
【讨论】:
以上是关于访问 UIButton 的子视图控件的主要内容,如果未能解决你的问题,请参考以下文章
UIButton 作为 MKAnnotationView 的子视图不起作用
为啥从自定义 UIView 向 UIButton 添加子视图不显示添加的子视图?