如何为iOS webView添加地址栏

时间:2016-05-08 12:54:40

标签: ios swift webview address-bar

在我的应用程序中有一个带默认网站google的webView。我在任何网页的某些应用中都看到顶部有一个地址栏,因此用户可以随时输入新的网址。我们怎么做?谢谢!

1 个答案:

答案 0 :(得分:0)

将您的网络视图放在UINavigationView内,然后将其headerView设置为UITextField。像这样:

class WebsiteViewController: UIViewController, UITextFieldDelegate {

  var addressField: UITextField? = nil

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

        addressField = ({
            let field = UITextField()
            field.autocorrectionType = UITextAutocorrectionType.No
            field.delegate = self
            field.addTarget(self, action: "addressChanged:", forControlEvents: .EditingChanged)
            field.addTarget(self, action: "addressEditEnded:", forControlEvents: .EditingDidEnd)
            field.sizeToFit()
            return field
        })()
    }

    override public func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        self.navigationItem.titleView = addressField
    }

    @IBAction func addressChanged(sender: UITextField) {
        if let newString = addressField?.text where newString != searchString && newString.characters.count != 1 {
            // do any filtering you might want to
        }
    }

    @IBAction func addressEditEnded(sender: UITextField) {
        // trigger the page load
    }
}

这应该涵盖必需品。