简体   繁体   English

NSTextView,绑定并显示NSString

[英]NSTextView, bindings and displaying an NSString

My second day working with Cocoa. 我和Cocoa合作的第二天。 I've got an NSTextView set up, its attributed string is bound to an NSArrayController (I'm using Core Data): 我已经设置了NSTextView,其属性字符串绑定到NSArrayController(我正在使用Core Data):

controller key: selection
model key path: myString

I've read that an NSTextView needs an NSAttributedString, which is why it's throwing an exception when trying to set the value of the attribute. 我已经读过NSTextView需要一个NSAttributedString,这就是为什么它在尝试设置属性的值时抛出异常。

NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "myString"; desired type = NSString; given type = NSConcreteAttributedString; 

Any ideas how I can get my managedObject's NSString attribute to be shown in an NSTextView? 任何想法如何让我的managedObject的NSString属性显示在NSTextView中?

You can bind your NSString to NSTextView's value instead of attributedString . 你可以绑定你的NSString NSTextView的value ,而不是attributedString For this, you need to turn off "Rich Text" for NSTextView. 为此,您需要为NSTextView关闭“Rich Text”。

You can use a NSValueTransformer subclass to go back and forth 您可以使用NSValueTransformer子类来回传递

@interface XXStringTransformer: NSValueTransformer {}
@end

@implementation XXStringTransformer
+ (Class)transformedValueClass 
{   
    return [NSAttributedString class]; 
}
+ (BOOL)allowsReverseTransformation 
{ 
    return YES; 
}
- (id)transformedValue:(id)value 
{
    return (value == nil) ? nil : [[[NSAttributedString alloc] initWithString:value] autorelease];
}

- (id)reverseTransformedValue:(id)value
{
    return (value == nil) ? nil : [[(NSAttributedString *)value string] copy];
}

@end

Caveat Emptor - This might be upside down and the reverser might leak. 警告Emptor - 这可能是倒置的,反向器可能会泄漏。 I just made it now but it should point you in the right direction. 我现在就做到了,但它应该指向正确的方向。 Let me know and ill correct the answer if its wrong. 如果错误的话,让我知道并纠正错误。

You can type the class name XXStringTransformer into the binding panel or do it programmatically. 您可以在绑定面板中键入类名XXStringTransformer或以编程方式执行。

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

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