我创建了一个.xib文件,其中包含一堆标签,可与SwipeView一起使用。我的问题是,在加载视图后,我无法知道如何访问和更改文本:
let newView = NSBundle.mainBundle().loadNibNamed("SwipeHelperView", owner: self, options: nil)[0] as UIView
for (var subview) in newView.subviews
{
if (subview.isKindOfClass(UILabel) && subview.tag == 0)
{
subview.text = "asdaS" //ERROR: cannot assign 'text' in 'subview'
}
}
现场创建标签会更容易吗:
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(0, 0)
label.text = "some text"
newView.addSubview(label)
而不是试图从" newView" UIView?是否有推荐的'方式还是关于prefferences?
答案 0 :(得分:2)
你应该施展它:
let newView = NSBundle.mainBundle().loadNibNamed("SwipeHelperView", owner: self, options: nil)[0] as UIView
for subview in newView.subviews as [UIView]
{
if subview.tag == 0
{
if let label = subview as? UILabel {
label.text = "asdaS"
}
}
}
如果您设置自定义标记(例如333),则可以按原样获取:
if let label = newView.viewWithTag(333) as? UILabel {
label.text = "TEST"
}
答案 1 :(得分:1)
两种方式都很好,但取决于你想要实现的目标。你可以这样做: -
您可以创建属性并从xib连接您的标签。稍后在您的代码中,您可以更改它的文本,如下所示: -
@IBOutlet var usernameLabel:UILabel! override func viewDidLoad(){ super.viewDidLoad() //在加载视图后进行任何其他设置,通常是从笔尖。 self.usernameTxt?.text =“some text” }
您可以通过编程方式创建并将其作为subView添加到视图中。代码: -
var label = UILabel(frame:CGRectMake(FRAME)) label.text =“一些文字” youView.addSubview(标签)
答案 2 :(得分:0)
it will be helpful if you make labels programmatically and add it in your newView.
var subview
for subview:AnyObject in newView.subviews
{
if (subview.isKindOfClass(UILabel) && subview.tag == 0)
{
var label=subview as UILabel
label.text="some text"
}
}