【问题标题】:Scrolling an NSScrollView while trying to preserve the position of a subview在尝试保留子视图的位置时滚动 NSScrollView
【发布时间】:2014-04-17 14:24:23
【问题描述】:

我有一个 NSScrollView 的子类。在该滚动视图的文档视图中,我有几个 NSView。最后,我在 documentView 中添加了一个名为 aView 的 NSView。

只要不需要滚动,我希望 aView 位于 documentView 的底部。只能沿 y 轴滚动。

如果 documentView 对 contentView 来说太高 - 所以需要滚动 - 我希望 aView 显示在 contentView 的底部。

这适用于您在下面看到的代码。

这是我的问题: 当我开始滚动时,我希望 aView 停留在 contentView 的底部,但 aView 只是与 documentView 中的所有其他视图一起滚动。 换句话说:如果需要滚动,我希望 aView 的 位置固定在我的 scrollView 可见矩形的底部,如果 contentView 足够高以显示整个文档视图。

有没有办法做到这一点?我哪里错了?

这是我的子类 NSScrollView 中的代码:

    [documentView addSubview:aView];

    aView.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint *documentAViewBottom = [NSLayoutConstraint constraintWithItem:documentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:aView attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
    documentAViewBottom.priority = NSLayoutPriorityDefaultHigh;
    [documentView addConstraint:documentAViewBottom];

    NSLayoutConstraint *aViewMaxYEdge = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:aView attribute:NSLayoutAttributeBottom multiplier:1 constant:5];
    [self addConstraint:aViewMaxYEdge];

    [documentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[aView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(aView)]];

【问题讨论】:

    标签: objective-c macos cocoa autolayout nsscrollview


    【解决方案1】:

    我有点老派,NSLayoutConstraints 对我没有吸引力,所以这里有一个替代建议的手动解决方案

    当您设置文档视图时,来自您的 NSScrollView 子类,

    [self.contentView setPostsBoundsChangedNotification:YES];
    

    然后订阅改变的边界

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentViewDidScroll:)
                                                         name:NSViewBoundsDidChangeNotification object:self.contentView];
    

    然后在

    -(void)contentViewDidScroll
    {
        double widthOfAView = aView.frame.size.width;
        double heightOfAView = aView.frame.size.height;
        [aView setFrameOrigin:NSMakePoint(NSMinX(self.contentView.bounds) - widthOfAView, NSMaxY(self.contentView.bounds) - heightOfAView)];
    }
    

    当然,所有这些都假设您的 isFlipped 被覆盖为 YES。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 2010-11-20
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多