在NSTableView文本单元格中创建并响应超链接

时间:2015-03-24 23:36:51

标签: objective-c macos swift nstableview nscell

我有一个程序,其中有一个NSTableView,其中填充了要上传的文件。发送文件后,带有文件名称的文本单元格将获得一个超链接(数组数据被赋予NSMutableString,其中包含NSLinkAttributeName属性)。如何允许用户单击此链接以在其默认浏览器中打开网页?

2 个答案:

答案 0 :(得分:2)

经过多次搜索和尝试多种方法,这就是我提出的解决方案。

创建扩展NSTableViewCell的自定义类:

class TableViewCellCursor: NSTableCellView {

internal var active = false

//MARK: - View Life Cycle

override func awakeFromNib() {
    superview?.awakeFromNib()
    self.createTrackingArea()
}

//MARK: - IBActions

override func mouseEntered(theEvent: NSEvent) {
    if (NSCursor.currentCursor() == NSCursor.arrowCursor() && active) {
        NSCursor.pointingHandCursor().set()
    }
}

override func mouseExited(theEvent: NSEvent) {
    if (NSCursor.currentCursor() == NSCursor.pointingHandCursor() && active) {
        NSCursor.arrowCursor().set()
    }
}

//Informs the receiver that the mouse cursor has moved into a cursor rectangle.
override func cursorUpdate(event: NSEvent) {
    if (active) {
        NSCursor.pointingHandCursor().set()
    }
}

//MARK: - Util

func createTrackingArea() {
    var focusTrackingAreaOptions:NSTrackingAreaOptions = NSTrackingAreaOptions.ActiveInActiveApp
    focusTrackingAreaOptions |= NSTrackingAreaOptions.MouseEnteredAndExited
    focusTrackingAreaOptions |= NSTrackingAreaOptions.AssumeInside
    focusTrackingAreaOptions |= NSTrackingAreaOptions.InVisibleRect

    var focusTrackingArea:NSTrackingArea = NSTrackingArea(rect: NSZeroRect,
                                                        options: focusTrackingAreaOptions,
                                                        owner: self, userInfo: nil)
    self.addTrackingArea(focusTrackingArea)
}
}

在NSTableView选择更改时检查第一响应者状态。这是必要的,因为表的选择可以改变,即使它不是第一个响应者:

func tableViewSelectionDidChange(aNotification: NSNotification) {
    if (self.firstResponder == filesToTransferTable) {
        changeSelectedRowTextColorTo(NSColor.whiteColor(), unselectedColor: NSColor.blueColor())
    } else {
        changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
    }
}

func changeSelectedRowTextColorTo(selectedColor: NSColor, unselectedColor: NSColor) {
    let selectedRows = filesToTransferTable.selectedRowIndexes
    for (index, tableEntry) in enumerate (tableData) {
        if tableData[index]["FileName"] is NSMutableAttributedString {
            var name = tableData[index]["FileName"] as! NSMutableAttributedString
            var range = NSMakeRange(0, NSString(string:name.string).length)
            name.beginEditing()
            name.removeAttribute(NSForegroundColorAttributeName, range: range)

            if (selectedRows.containsIndex(index)) {
                name.addAttribute(NSForegroundColorAttributeName, value:selectedColor, range:range)
            } else {
                name.addAttribute(NSForegroundColorAttributeName, value:unselectedColor, range:range)
            }

            name.endEditing()
            tableData[index]["FileName"] = name
        }
        filesToTransferTable.reloadDataForRowIndexes(NSIndexSet(index: index), columnIndexes: NSIndexSet(index:0))
    }
}

添加KVO以检查FirstResponder何时更改:

//This is somewhere in your code where you initialize things
//KVO for first responder behavior regarding tableView and updating attributedStrings' colors
self.addObserver(self, forKeyPath: "firstResponder", options: NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, context: nil)

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
            if (change[NSKeyValueChangeNewKey] is NSTableView) {
                changeSelectedRowTextColorTo(NSColor.whiteColor(), unselectedColor: NSColor.blueColor())
            } else if (change[NSKeyValueChangeOldKey] is NSTableView) {
                changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
            }
        }

最后,检查主窗口(应用程序本身)是否处于焦点(如果没有这样做,那么当窗口失去焦点时,颜色不会发生相应的变化):

//Put these in the same place as the KVO code
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidBecomeKey:",
                    name: NSWindowDidBecomeKeyNotification , object: self)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidResignKey:",
                    name: NSWindowDidResignKeyNotification , object: self)


    func windowDidBecomeKey(notification: NSNotification) {
        if (self.firstResponder == filesToTransferTable) {
            changeSelectedRowTextColorTo(NSColor.whiteColor(), unselectedColor: NSColor.blueColor())
        } else {
            changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
        }
    }

    func windowDidResignKey(notification: NSNotification) {
        if (self.firstResponder == filesToTransferTable) {
            changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
        }
    }

答案 1 :(得分:0)

文本字段自动支持单击嵌入的链接,但仅限于它们至少是可选择的(如果不可编辑)。因此,请将文本字段设置为可选。