如何从UIScrollView中查找和替换子视图

时间:2017-08-20 13:58:48

标签: ios iphone swift uiview uiscrollview

我有一个滚动视图,我在ViewDidLoad中添加了4个子视图,现在在应用程序使用期间,我想用新视图替换其中一个子视图。

我正在尝试将标记添加到子视图并找到并替换,但似乎找不到标记。也无法找到替换视图的正确方法

let subViews = self.scrollView.subviews
for subview in subViews{
    if subview.tag == 1000 {
        let tempView = subview
        tempView = newView
    }
}

我确信上面的代码不正确,这里代码永远不会进入'if',当我看到调试区域中的所有子视图时,我也看不到标签。

来自ViewDidLoad的

代码

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        self.overLeftVc = storyboard.instantiateViewController(withIdentifier: "settingViewController")
        self.leftVc = storyboard.instantiateViewController(withIdentifier: "giftCardListViewController")
        self.middleVc = storyboard.instantiateViewController(withIdentifier: "redeemViewController")
        self.rightVc = storyboard.instantiateViewController(withIdentifier: "homeViewController")
        self.overRightVc = storyboard.instantiateViewController(withIdentifier: "ticketListViewController")

        let isShowBotView = self.config.getValue("isSystemGenerated", fromStore: "settings") as! Bool

        if isShowBotView == true {
            self.nextOfOverRightVc = storyboard.instantiateViewController(withIdentifier: "chatViewController")
        }
        else {
            self.nextOfOverRightVc = storyboard.instantiateViewController(withIdentifier: "tileMainViewController")
        }

        self.nextOfOverRightVc.view.tag = 1000



            addChildViewController(overLeftVc)
            addChildViewController(leftVc)
            addChildViewController(middleVertScrollVc)
            addChildViewController(nextOfOverRightVc)
          //  addChildViewController(tileMainRightVc)

            scrollView.addSubview(overLeftVc.view)
            scrollView.addSubview(leftVc.view)
            scrollView.addSubview(middleVertScrollVc.view)
            scrollView.addSubview(nextOfOverRightVc.view)

1 个答案:

答案 0 :(得分:0)

将子视图的帧保存在变量中,删除该子视图并在该帧处插入新的子视图

for subview in subViews{
if subview.tag == 1000 {
    self.frameOfViewToBeReplaced = subview.frame
    subview.removeFromSuperView()
     }
 }
 let newView = UIView(frame : self.frameOfViewToBeReplaced)