使用自定义NSTextBlock保存和粘贴属性字符串

问题描述 投票:6回答:1

我正在尝试创建自定义NSTextBlock,就像Apple在WWDC 18(23 mins in)上所做的那样。

Full demo project here

[好,所以当我用段落样式附加了文本块的段落进行编辑和标记时,它非常有用。

enter image description here

但是当我剪切并粘贴它(或从磁盘归档/取消归档)时,它会丢失。编辑:实际上它把我的TweetTextBlock子类变成了NSTableViewTextBlock,这也解释了边框。

enter image description here

实施

Here's a full Xcode project。使用Format顶部菜单项触发markTweet功能。

这是将属性添加到段落中的方法

    @IBAction func markTweet(_ sender : Any?){
    print("now we are marking")
    let location = textView.selectedRange().location


    guard let nsRange = textView.string.extractRange(by: .byParagraphs, at: location) else { print("Not in a paragraph"); return }

    let substring = (textView.string as NSString).substring(with: nsRange)

    let tweetParagraph = NSMutableParagraphStyle()
    tweetParagraph.textBlocks = [TweetTextBlock()]

    let twitterAttributes : [AttKey : Any] = [
        AttKey.paragraphStyle : tweetParagraph,
        AttKey.font : NSFont(name: "HelveticaNeue", size: 15)
    ]

    textView.textStorage?.addAttributes(twitterAttributes, range: nsRange)
}

这是我的NSTextBlock子类

import Cocoa

class TweetTextBlock: NSTextBlock {

    override init() {
        super.init()
        setWidth(33.0, type: .absoluteValueType, for: .padding)
        setWidth(70.0, type: .absoluteValueType, for: .padding, edge: .minX)

        setValue(100, type: .absoluteValueType, for: .minimumHeight)

        setValue(300, type: .absoluteValueType, for: .width)
        setValue(590, type: .absoluteValueType, for: .maximumWidth)


        backgroundColor = NSColor(white: 0.97, alpha: 1.0)

    }


    override func drawBackground(withFrame frameRect: NSRect, in controlView: NSView,
        characterRange charRange: NSRange, layoutManager: NSLayoutManager) {

        let frame = frameRect
        let fo = frameRect.origin

        super.drawBackground(withFrame: frame, in: controlView, characterRange:
        charRange, layoutManager: layoutManager)

        // draw string
        let context = NSGraphicsContext.current
        context?.shouldAntialias = true

        let drawPoint: NSPoint = CGPoint(x: fo.x + 70, y: fo.y + 10)


        let nameAttributes = [AttKey.font: NSFont(name: "HelveticaNeue-Bold", size: 15),  .foregroundColor: NSColor.black]
        var handleAttributes = [AttKey.font: NSFont(name: "HelveticaNeue", size: 15),  .foregroundColor: NSColor(red: 0.3936756253, green: 0.4656872749, blue: 0.5323709249, alpha: 1)]

        let nameAStr = NSMutableAttributedString(string: "Johanna Appleseed", attributes: nameAttributes)
        let handleAStr = NSAttributedString(string: "  @johappleseed ·  3h", attributes: handleAttributes)
        nameAStr.append(handleAStr)
        nameAStr.draw(at: drawPoint)

        let im = NSImage(named: "profile-twitter")!
        im.draw(in: NSRect(x: fo.x + 10, y: fo.y + 10, width: 50, height: 50))

        }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

}

我尝试了什么

我的想法是,可能发生这种情况,因为TextKit不知道如何从自定义块中存档属性。但是我尝试覆盖init:fromCoderencode。他们不打电话。不可复制,粘贴,存档,取消存档。所以我想不是那样的。这使我认为所有这些自定义绘图逻辑都无法保存在属性字符串中,而这一切都发生在布局管理器中。那讲得通。但是我该如何坚持呢?

更新:我尝试读取属性。它具有段落样式,并且该段落样式在textBlocks数组属性中具有一个项目。但是该文本块是NSTextBlock,而不是我的子类(我尝试过if block is TweetTextBlock,它返回false)

更新2:我尝试覆盖classForArchiver之类的属性,然后使用例如print("twb: Class for archiver", block.classForArchiver)。有趣的是,文本块已变成NSTextTableBlock!我现在非常擅长破解这个问题,以至于我正在寻找一种在文本块中存储className somewhere的方法。到目前为止,我唯一能想到的就是tooltip属性,但这对用户是可见的,我可能想将其用于其他用途。

更新3:也不会保留工具提示。那真是怪了。我能想到的下一个大技巧是将文本颜色设置为HSB(n,0,0),其中n是NSTextBlock子类的标识符。希望我不必去那里。

UPDATE 4.这很可能是由于归档以及复制/粘贴将字符串转换为RTF所引起的。这是我剪贴板中的public.rtf

{\rtf1\ansi\ansicpg1252\cocoartf2509
\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;}
{\colortbl;\red255\green255\blue255;\red245\green245\blue245;}
{\*\expandedcolortbl;;\csgray\c97000;}
\pard\intbl\itap1\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\pardirnatural\partightenfactor0

\f0\fs30 \cf0 THIS text is in a TweetTextBlock}
swift nsattributedstring nstextview textkit nslayoutmanager
1个回答
0
投票

看来NSAttributedString有点不对劲。我尝试将NSMutableParagraphStyle子类化并使用它,并且it未被编码或解码(初始化)。

可能有可能使用自定义Attribute.Key来简单地注释运行的文本,以指示块内容及其“类型”的轮廓,然后在粘贴后对AttributedString进行后处理。

或者,现成的Pasteboard类型可能不支持NSAttributedString并已存档。相反,(而且我猜)最高保真度的文本类型可能是RTF,这可能说明根本没有调用TextBlock NSCoding方法的事实。

NSPasteboard.PasteboardType,我的投票是选项2。

© www.soinside.com 2019 - 2024. All rights reserved.