Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/110.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 向WebView添加约束时出错-Swift_Ios_Swift_Webkit - Fatal编程技术网

Ios 向WebView添加约束时出错-Swift

Ios 向WebView添加约束时出错-Swift,ios,swift,webkit,Ios,Swift,Webkit,我正在用swift练习Webkit。我跟随是为了同样的目的。我在代码的前几行中遇到了一个错误 这是迄今为止我在ViewController.swift中看到的: import UIKit import WebKit class ViewController: UIViewController { var webView : WKWebView required init(coder aDecoder: NSCoder) { self.webView = WKWebView(fram

我正在用swift练习Webkit。我跟随是为了同样的目的。我在代码的前几行中遇到了一个错误

这是迄今为止我在ViewController.swift中看到的:

import UIKit
import WebKit

class ViewController: UIViewController {

var webView : WKWebView

required init(coder aDecoder: NSCoder) {
    self.webView = WKWebView(frame: CGRectZero)
    super.init(coder: aDecoder)!
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(webView)
    webView.translatesAutoresizingMaskIntoConstraints = false
    let height = NSLayoutConstraint(item: webView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: 0)
    let width = NSLayoutConstraint(item: webView, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0)
    webView.addConstraints([height,width])

    let url = NSURL(string: "http://www.google.com")
    let urlRequest = NSURLRequest(URL: url!)
    webView.loadRequest(urlRequest)

}

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


}
以下是控制台错误输出的外观:

2016-10-27 11:29:09.015 Browser[68308:1113663] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***
+[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Constraint items must each be an instance of UIView, or NSLayoutGuide.'
*** First throw call stack: (   0   CoreFoundation                      0x00000001060e0d85 __exceptionPreprocess + 165  1   libobjc.A.dylib    0x0000000108486deb objc_exception_throw + 48     2   CoreFoundation       0x00000001060e0cbd +[NSException raise:format:] + 205  3   Foundation  0x00000001064af0ac +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]
+ 277   4   Browser                             0x0000000105ef890b _TTOFCSo18NSLayoutConstraintCfT4itemPs9AnyObject_9attributeOSC17NSLayoutAttribute9relatedByOSC16NSLayoutRelation6toItemGSqPS0___9attributeS1_10multiplierV12CoreGraphics7CGFloat8constantS4__S_
+ 123   5   Browser                             0x0000000105ef78ee _TFC7Browser14ViewController11viewDidLoadfT_T_ + 494     6   Browser                             0x0000000105ef7c12 _TToFC7Browser14ViewController11viewDidLoadfT_T_ + 34    7   UIKit                               0x0000000106aa5984
-[UIViewController loadViewIfRequired] + 1198   8   UIKit                               0x0000000106aa5cd3 -[UIViewController view] + 27    9   UIKit            0x000000010697bfb4 -[UIWindow addRootViewControllerViewIfPossible] + 61    10  UIKit                               0x000000010697c69d
-[UIWindow _setHidden:forced:] + 282    11  UIKit                               0x000000010698e180 -[UIWindow makeKeyAndVisible] + 42   12  UIKit       0x0000000106902ed9 -[UIApplication
_callInitializationDelegatesForMainScene:transitionContext:] + 4131     13  UIKit                               0x0000000106909568
-[UIApplication _runWithMainScene:transitionContext:completion:] + 1769     14  UIKit                               0x0000000106906714
-[UIApplication workspaceDidEndTransaction:] + 188  15  FrontBoardServices                  0x000000010a3558c8
__FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24   16  FrontBoardServices                  0x000000010a355741
-[FBSSerialQueue _performNext] + 178    17  FrontBoardServices                  0x000000010a355aca -[FBSSerialQueue _performNextFromRunLoopSource] + 45     18  CoreFoundation                      0x0000000106006301
__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17     19  CoreFoundation                      0x0000000105ffc22c
__CFRunLoopDoSources0 + 556     20  CoreFoundation                      0x0000000105ffb6e3 __CFRunLoopRun + 867     21  CoreFoundation            0x0000000105ffb0f8 CFRunLoopRunSpecific + 488     22  UIKit               0x0000000106905f21 -[UIApplication _run] + 402  23  UIKit              0x000000010690af09 UIApplicationMain + 171   24  Browser                0x0000000105ef92f2 main + 114    25  libdyld.dylib                       0x0000000108f5d92d start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException
我是个初学者,所以不用说,我不知道这意味着什么。 此外,我还收到了错误消息
线程1:SIGABRT信号
,如果我忽略删除先前创建的出口引用,通常会得到该信号。在这种情况下,我没有创建任何出口

在目标C中,我已经在堆栈上查看了一些关于类似问题的其他答案,但我不能很好地理解它


我知道解决方案可能相对简单,但任何帮助都将不胜感激

每个视图都需要4个约束,以便系统可以计算:x、y、width、height(标签和图像视图已经具有内在尺寸,但如果需要,仍然可以约束它们)。以下是webview的4个约束条件:

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        let attributes: [NSLayoutAttribute] = [.centerX, .centerY, .width, .height]
        NSLayoutConstraint.activate(attributes.map {NSLayoutConstraint(item: webView, attribute: $0, relatedBy: .equal, toItem: webView.superview, attribute: $0, multiplier: 1, constant: 0) })
        let url = URL(string: "http://www.google.com")!
        let urlRequest = URLRequest(url: url)
        webView.load(urlRequest)
    }

所以我终于修正了代码!这是正确的代码

import UIKit
import WebKit
class ViewController: UIViewController {    
    var webView : WKWebView
    required init(coder aDecoder: NSCoder) {
        self.webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 414, height: 736))
        super.init(coder: aDecoder)!
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        let views = ["webView" : webView]
        let h = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: [], metrics: nil , views: views)
        let w = NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: [], metrics: nil, views: views)
        view.addConstraints(h)  //This is where I was going wrong
        view.addConstraints(w)  //This is where I was going wrong 
        let url = NSURL(string: "http://www.google.com")
        let urlRequest = NSURLRequest(URL: url!)
        webView.loadRequest(urlRequest)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

原来我是在
webView
中添加约束的,我本应该在
view
中添加约束的。我不确定我是否完全理解这段代码的工作原理。它没有运行,我使用的是Swift 2.1,所以我必须稍微修改一下代码。我会让你知道它是否有效。但是我没有得到
$0
的功能。map将属性转换为NSLayoutConstraints$0是代表属性数组中每个元素的默认参数。它在swift 2中工作。您必须将swift 2的所有NSLayoutAttribute枚举大写,并将URL和URLRequest更改回NSURL和NSURLRequest<代码>NSLayoutConstraint.activateConstraints(attributes.map({NSLayoutConstraint(项:webView,属性:$0,relatedBy:.Equal,toItem:webView,属性:$0,乘数:1,常数:0)}))它编译但只显示一个空视图。我做错了什么?NSLayoutConstarint没有activate属性,这就是为什么我将其更改为ActivateConstraints,这意味着webview就在那里。你的负载有问题。将静态文本放入其中以测试(使用更大的字符串)webView.loadHTMLString(“测试”,baseURL:nil)