开发者

NSNotification Scrolling - User vs Programmatic

开发者 https://www.devze.com 2023-04-09 04:13 出处:网络
I have a program with an NSTextView (actually, a custom subclass) into which a lot of lines of data are likely to be programmatically inserted. (It reads a stream of serial data from a USB port.) I ha

I have a program with an NSTextView (actually, a custom subclass) into which a lot of lines of data are likely to be programmatically inserted. (It reads a stream of serial data from a USB port.) I have a checkbox for enabling/disabling autoscrolling. I want to allow the user to break out of autoscrolling simply by trying to scroll back up. So, I need a notification that tells me when 开发者_如何转开发the user has scrolled, not just when the bounds have changed, since this happens every time more serial data gets inserted. Is this possible?


Surely you could use the notification that tells you when any scrolling takes place, and then check if the text view is scrolled entirely to the bottom? If it is, turn auto-scrolling on. If not, turn it off.


It's not the best, but this works in my case. I think it could be done a little cleaner with some NSEvent manipulation, but I realized that I can check to see if the user has started scrolling by checking the current scroll position against the total document rectangle height.

NSRect totalRect   = [[serialScrollView contentView] documentRect];
NSRect visibleRect = [[serialScrollView contentView] documentVisibleRect];
NSInteger totalHeight = totalRect.size.height;
NSInteger visibleHeight = visibleRect.size.height;
NSInteger position = visibleRect.origin.y;

NSInteger scrollPoint = position + visibleHeight;

if (totalHeight != scrollPoint)
    [autoscrolls setState:0];

So basically, if the scroll position becomes anything other than what the program expects it to be from programmatic writes, it turns autoscrolling off. A cool thing about this implementation is that if you ad an else [autoscrolls setState:1];, it turns autoscrolling back on when you scroll back down to catch up with the stream. This emulates the scrolling behavior in the terminal when you're running a shell script with lots of output, like a yum install on Fedora or that sort of thing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号