简体   繁体   English

如何在 Swift 中访问 NSTableCellView 中的 ImageView?

[英]How do I access an ImageView within an NSTableCellView in Swift?

I'm trying to programmatically populate the cells of a column with images already defined in an array (flags).我正在尝试使用已在数组(标志)中定义的图像以编程方式填充列的单元格。

In IB I have an Image View directly within a Table Cell View.在 IB 中,我在表格单元格视图中直接有一个图像视图。 In the ViewController this is what I'm doing:在 ViewController 这就是我在做什么:

   public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
      
      guard let cellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView else { return nil }
      
      if tableColumn?.title == "flag" {
         cellView.imageView?.image = NSImage(named: flags[row])   // NOT WORKING
      } else if tableColumn?.title == "country" {
         cellView.textField?.stringValue = flags[row].uppercased()
      }
      
      return cellView
   }

This results in the text field cells in the "country" column getting set fine, but each of the cells in the "flag" column all have the default image I set in IB--or nothing if I take that out.这导致“国家/地区”列中的文本字段单元格设置得很好,但“标志”列中的每个单元格都具有我在 IB 中设置的默认图像——或者如果我将其删除,则什么都没有。

According to the tutorials and StackOverflow posts I've looked through, it seems that I'm doing everything right--but obviously I've messed up something.根据我浏览过的教程和 StackOverflow 帖子,似乎我做的一切都是正确的——但显然我搞砸了一些事情。

(In response to the screen cast shared in the comments) (回应评论中分享的截屏)

Notice how that Image View (in the cell) is not referenced by anything (its "Referencing Outlets" section on the right is empty).请注意图像视图(在单元格中)没有被任何内容引用(其右侧的“引用插座”部分为空)。

Your image view is a subview of its cell (as indicated by its position in the view heiarchy on the left side bar), so you could presumably access it using something like:您的图像视图是其单元格的子视图(如其在左侧栏上的视图层次结构中的位置所示),因此您大概可以使用以下内容访问它:

let imageView = cell.subViews.first(where: { $0 is NSImageView }) as! NSImageView
imageView.image = NSImage(named: flags[row])

...but that's obviously clunky. ……但这显然很笨拙。

Instead, you should select your cell, and drag from its imageView outlet, to the Image View.相反,您应该选择您的单元格,然后从其imageView出口拖到 Image View。 This will make a new reference, which will make cell.imageView non-nil.这将创建一个新的引用,这将使cell.imageView非零。

Alternatively, I would suggest you just delete your cell, and create a new one from the "Image & Test Table Cell View" from the "Object Library".或者,我建议您删除单元格,然后从“对象库”的“图像和测试表单元格视图”创建一个新单元格。 It'll have all the outlets hooked up already.它已经连接了所有的插座。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM