NSTextView突出显示不会触发

时间:2012-12-26 22:30:01

标签: python objective-c cocoa

我已下载:NSTextView突出显示:enter link description here

它可以正常工作,如果你打开应用程序并输入符号“ - ”它会变成红色,但后来我遇到了问题。我在 .h 文件中写了IBOutlet NSTextView * change_text并写在 .m 文件中:

-(void)awakeFromNib {



    [text_View setString:@"-"];


}

这个想法是当应用程序打开时它应该在屏幕上显示红色的“ - ”符号。它确实显示了标志:“ - ”但没有突出显示它,直到我手动点击返回或空格然后它变成红色。我希望它将标志变为红色,而不是等待有人再次更改文本。请帮帮我

python脚本看起来像:

from Foundation import *
from AppKit import *

import objc

class PyObjC_HighlightAppDelegate(NSObject):

    # The connection to our NSTextView in the UI
    highlightedText = objc.IBOutlet()

    # Default font size to use when highlighting
    fontSize = 12

    def applicationDidFinishLaunching_(self, sender):
        NSLog("Application did finish launching.")

    def textDidChange_(self, notification):




        """
        Delegate method called by the NSTextView whenever the contents of the
        text view have changed. This is called after the text has changed and
        been committed to the view. See the Cocoa reference documents:

        http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSText_Class/Reference/Reference.html
        http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextView_Class/Reference/Reference.html

        Specifically the sections on Delegate Methods for information on additional
        delegate methods relating to text control is NSTextView objects.
        """

        # Retrieve the current contents of the document and start highlighting

        content = self.highlightedText.string()
        self.highlightText(content)

    def setAttributesForRange(self, color, font, rangeStart, rangeLength):
        """
        Set the visual attributes for a range of characters in the NSTextView. If
        values for the color and font are None, defaults will be used.

        The rangeStart is an index into the contents of the NSTextView, and
        rangeLength is used in combination with this index to create an NSRange
        structure, which is passed to the NSTextView methods for setting
        text attributes. If either of these values are None, defaults will
        be provided.

        The "font" parameter is used as an key for the "fontMap", which contains
        the associated NSFont objects for each font style.
        """
        fontMap = {
                    "normal" : NSFont.systemFontOfSize_(self.fontSize),
                    "bold" : NSFont.boldSystemFontOfSize_(self.fontSize)
                    }

        # Setup sane defaults for the color, font and range if no values
        # are provided
        if color is None:
            color = NSColor.blackColor()
        if font is None:
            font = "normal"        

        if font not in fontMap:
            font = "normal"

        displayFont = fontMap[font]

        if rangeStart is None:
            rangeStart = 0

        if rangeLength is None:
            rangeLength = len(self.highlightedText.string()) - rangeStart

        # Set the attributes for the specified character range
        range = NSRange(rangeStart, rangeLength)
        self.highlightedText.setTextColor_range_(color, range)
        self.highlightedText.setFont_range_(displayFont, range)

    def highlightText(self, content):
        """
        Apply our customized highlighting to the provided content. It is assumed that
        this content was extracted from the NSTextView.
        """

        # Calling the setAttributesForRange with no values creates
        # a default that "resets" the formatting on all of the content
        self.setAttributesForRange(None, None, None, None)

        # We'll highlight the content by breaking it down into lines, and
        # processing each line one by one. By storing how many characters
        # have been processed we can maintain an "offset" into the overall
        # content that we use to specify the range of text that is currently
        # being highlighted.
        contentLines = content.split("\n")
        highlightOffset = 0

        for line in contentLines:

            if line.strip().startswith("#"):
                # Comment - we want to highlight the whole comment line
                self.setAttributesForRange(NSColor.greenColor(), None, highlightOffset, len(line))


            elif line.find(":") > -1:
                # Tag - we only want to highlight the tag, not the colon or the remainder of the line
                startOfLine = line[0: line.find(":")]
                yamlTag = startOfLine.strip("\t ")
                yamlTagStart = line.find(yamlTag)
                self.setAttributesForRange(NSColor.blueColor(), "bold", highlightOffset + yamlTagStart, len(yamlTag))

            elif line.strip().startswith("-"):
                # List item - we only want to highlight the dash
                listIndex = line.find("-")
                self.setAttributesForRange(NSColor.redColor(), None, highlightOffset + listIndex, 1)


            # Add the processed line to our offset, as well as the newline that terminated the line
            highlightOffset += len(line) + 1

2 个答案:

答案 0 :(得分:1)

我认为这里的核心问题是调用-[NSTextView setString]不会发布NSTextDidChangeNotification,因此代码永远不会调用textDidChange_方法。所以我认为最简单的解决方案就是在设置字符串后发布通知。我真的不知道PyObjC,但这就是你在Objective-C中的表现:

[[NSNotificationCenter defaultCenter] postNotificationName:NSTextDidChangeNotification object:text_view];

我不建议直接调用方法textDidChange_方法,就像您(或您使用的任何库)依赖于文本更改时调用的方法一样,它们需要对同一通知作出反应。 / p>

答案 1 :(得分:-2)

如果我理解正确的话,只需在textDidChange中调用applicationDidFinishLaunching即可。