在 TableView 中找不到 UIWebView

Can't find UIWebView in a TableView

我正在尝试在 table 单元格中显示网络视图。 在 "let webView = cell.viewWithTag(12) as! UIWebView" 处弹出错误 Unexpectedly found nil while unwrapping optional。 webView 的标签是 12(交叉检查了很多次)。 dateLabel 和 captionLabel 工作正常。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell : UITableViewCell!
    cell = tableView.dequeueReusableCellWithIdentifier("idCellPost", forIndexPath: indexPath)
    let dateLabel = cell.viewWithTag(10) as! UILabel
    let captionLabel = cell.viewWithTag(11) as! UILabel
    let webView = cell.viewWithTag(12) as! UIWebView
    dateLabel.text = "8/18/2015"
    captionLabel.text = "Dummy text."
    webView.loadRequest(getRequest())
    webView.scalesPageToFit = true
    return cell
}

您已经创建了自定义单元格。您不需要使用标签访问它的子视图。您可以直接将它们作为属性访问。

    if let customCellObject = tableView.dequeueReusableCellWithIdentifier("idCellPost", forIndexPath: indexPath) as? CustomCell  {
        customCellObject.dateLabel?.text = "8/18/2015"
        customCellObject.captionLabel?.text = "Dummy text."
        customCellObject.webView?.loadRequest(getRequest())
        return customCellObject
    }

当然,在 if 块之外,如果您的自定义单元格没有出列,您需要处理这种情况。

let dateLabel: UILabel = UILabel() 
let captionLabel:UILabel = UILabel()
let webView : UIWebView = UIWebView(frame: cell.frame) 

dateLabel.text = "8/18/2015"
captionLabel.text = "Dummy text."
webView.loadRequest(getRequest())
webView.scalesPageToFit = true
[cell.addSubview(webView)];

//你应该有 viewWithTag 10 和 11。

func getRequest()-> NSURLRequest!{
let urlPath: String = "http://www.google.com"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
return request1
}

在“实用程序”选项卡的文件检查器下取消选中“使用大小 类”。现在工作正常。出于某种原因,当检查尺寸 类 时,ViewWithTag returns 为零。