简体   繁体   English

如何使用Swift从同一Xib访问UIView

[英]How to access UIView from the same xib using swift

Let me explain my problem here, I am working on a project in which I am having a xib file with a UIView. 让我在这里解释我的问题,我正在一个项目中,我有一个带有UIView的xib文件。 What I have done is, I created another UIView inside the same xib and I need to show that in my xib view in a button action using swift. 我要做的是,我在同一个xib中创建了另一个UIView,我需要使用swift在按钮操作中的xib视图中显示它。

Note : If I tend to do this via programatically it is working fine but the problem while I am doing with my xib. 注意:如果我倾向于通过编程方式执行此操作,则可以正常工作,但使用xib时出现问题。 (testview) is a view that I have created inside the xib. (testview)是我在xib内部创建的视图。

 class tableClass: UIViewController {

    @IBOutlet var testview : UIView

    override func viewDidLoad() {
       super.viewDidLoad()
       println(testview)    **///// Return nil  /////**
       testview=UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) as UIView

       println(testview)    **///// Return nil  /////**
       self.view.bringSubviewToFront(testview)
       self.view.addSubview(testview)
     }
 }

Thanks in Advance. 提前致谢。 Please let me know, your answers and valuable ideas. 请让我知道,您的回答和宝贵的想法。

I solved the above stated problem by initializing my UIView in ViewDidLoad method. 我通过在ViewDidLoad方法中初始化UIView解决了上述问题。 Here, is the lines I wrote on my didLoad method 这是我在didLoad方法上写的行

class tableClass: UIViewController {

@IBOutlet var testview : UIView = nil

override func viewDidLoad() {
   super.viewDidLoad()
   testview.frame = CGRectMake(0, 0, 0, 0)
   self.view.addSubview(testview)
 }}

After doing that, I can able to change the UIView frame anywhere from the class, like below. 之后,我可以在类的任何地方更改UIView框架,如下所示。 Happy Coding.. 快乐编码

testview.backgroundColor = UIColor.greenColor()
testview.frame = CGRectMake(50, 50, 50, 50)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM