通过单击子视图中的按钮来更改UIView显示

时间:2018-07-02 09:05:49

标签: ios

我在CreateAccountViewController中初始化了一个UIView

Web

当我单击UIView幻灯片中的btn按钮时,我想为此UIView添加新的UUBiew     我实现如下并得到

  

1 addview错误=无。

有人可以帮我吗?

import UIKit

class CreateAccountViewController: UIViewController {

    @IBAction func btnAdd(sender: AnyObject) {
        let subview = NSBundle.mainBundle().loadNibNamed("Slide", owner: self, options: nil)?.first as! Slide
        self.addview.addSubview(subview)

    }
    @IBOutlet weak var addview: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

1 个答案:

答案 0 :(得分:0)

我假设您已经为SlideTest创建了XIB文件。您可以使用协议委托方法来实现代码。创建幻灯片视图的协议方法,并通过创建委托,您可以通过调用相同的委托协议方法来访问视图控制器中的btn点击。

class CreateAccountViewController: UIViewController, SlideDelegate {

    @IBOutlet weak var addview: UIView!

    // Create Global Variable to access in delegate method of SlideDelegate
     var slideView: Slide?

    @IBAction func btnAdd(sender: AnyObject) {
        slideView = Bundle.main.loadNibNamed("Slide", owner: self, options: nil)![0] as? Slide
        slideView?.delegate = self
        self.addview.addSubview(slideView!)
    }

    func add(view: Test) {
        if slideView != nil {
            slideView?.addSubview(view)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

创建协议如下;

protocol SlideDelegate: class {
    func add(view: Test)
}


class Slide: UIView {

    @IBOutlet weak var txtTen: UILabel!
    @IBOutlet weak var imageHinhAnh: UIImageView!
    @IBOutlet weak var txtNoiDung: UILabel!

    weak var delegate: SlideDelegate?

    @IBAction func btn(sender: AnyObject) {
        let subview = Bundle.main.loadNibNamed("Test", owner: self, options: nil)![0] as! Test

        if let selfDelegate = delegate {
            // Call delegate method which will notify your view controller to add sub view
            selfDelegate.add(view: subview)
        }
    }
}