Search code examples
iosswiftuiwebview

Assigning a webview to a subview


I was following a tutorial about WKWebViews (https://www.hackingwithswift.com/read/4/2/creating-a-simple-browser-with-wkwebview) and I wanted to change this line

view = webview

by

view.subviews[0].subviews[0] = webview

Because I want the webbrowser to be in that particular view. However, XCode complains about it saying: "Cannot assign through subscript: 'subviews' is a get-only property".

Why does it work with the highest view and it doesn't with the other ones? Is there a way to edit subviews so I can assign the webview to the subview I want? Because I've seen that it is possible to remove subviews so it's not like it's a read-only property.


Solution

  • You can't directly assign the readonly property. Instead of doing this. view.subviews[0].subviews[0] = webview

    Just add the webviews as subview to your main view.

    let rootView = view.subviews[0]
    rootView.addSubview(webView)
    rootView.bringSubview(toFront:webView)
    

    Else do the below

    rootView.insertSubview(webView, at: 0)