【问题标题】:NSTextView scrolling behavior and selecting behaviorNSTextView 滚动行为和选择行为
【发布时间】:2017-05-05 03:39:33
【问题描述】:

我有一个从 NSTask 输出文本的 NSTextView。除了滚动和选择行为之外,一切都按预期工作。

1:如果我尝试向上滚动,我的滚动位置会在我松开后立即弹回底部。有任何想法吗?我浏览了很多关于此的文档,但找不到任何关于它的信息。

2:如果我选择文本,它会删除它。我只想选择它,以便我可以复制和粘贴。这个也迷路了。

任何提示或指示都将受到欢迎。谢谢。

- (id)init
{
    [super init];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(readPipe:)
                                                 name:NSFileHandleReadCompletionNotification 
                                               object:nil];

    return self;
}

- (void)kicked
{
    task = [[NSTask alloc] init];

    [task setLaunchPath:[self.kickLocationTextField stringValue]];
    [task setArguments:kickBuild];

    NSPipe *pipe = [[NSPipe alloc] init];
    fileHandle = [pipe fileHandleForReading];
    [fileHandle readInBackgroundAndNotify];

    [task setStandardOutput:pipe];
    [task setStandardError:pipe];

    [task launch];

    [task release];
    [pipe release];
}


- (void)readPipe:(NSNotification *)notification
{
    NSData *data;
    NSString *text;

    if( [notification object] != fileHandle )
    {
        return;
    }

    data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
    text = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    [nsTaskOutput insertText:text];

    [text release];
    if (data != 0)
    {
        [fileHandle readInBackgroundAndNotify];
    }
}

【问题讨论】:

  • 每当您从任务中获得输出时,您是否会替换文本视图中的整个文本?请编辑问题并发布用于从任务中获取输出并将其添加到文本视图的代码。
  • 已更新。根据 NSTextView 的文档...如果在视图中没有选择任何内容,它将附加下一个传入的字符串。如果有选定的文本...它将替换它。除了前两个问题之外,一切都按预期进行。

标签: objective-c cocoa nstextview


【解决方案1】:

试试这个而不是insertText::

NSScroller *scroller = nTaskOutput.enclosingScrollView.verticalScroller;
BOOL shouldScrollToBottom = scroller.doubleValue == 1.0;
NSTextStorage *ts = nTaskOutput.textStorage;
[ts replaceCharactersInRange:NSMakeRange(ts.length, 0) withString:text];
if (shouldScrollToBottom) {
    NSRect bounds = nTaskOutput.bounds;
    [nTaskOutput scrollPoint:NSMakePoint(NSMaxX(bounds), NSMaxY(bounds))];
}

【讨论】:

  • 不错!效果很好!!唯一的缺点是它不会自动滚动到底部并显示新的输出。
  • 我已经修改了我的答案,但这只是一个猜测。
  • 宾果游戏!我将不得不分解你在这里做了什么。我从未使用过 NSTextStorage 或 NSScroller,所以看起来是时候深入研究文档的这些部分了。非常感谢罗。
  • 看起来你的滚动到底部实现相当于“如果(滚动在底部)然后滚动到底部”对吗?
  • 这更像是“如果在插入前滚动到底部,然后在插入后滚动到底部。”
猜你喜欢
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
相关资源
最近更新 更多