【问题标题】:How to make UILabel position fixed?如何使 UILabel 位置固定?
【发布时间】:2018-04-19 18:49:18
【问题描述】:

我在 Xcode 的 Interface Builder 中将“标签”对象拖到我故事板中的场景中。

问题是 Label 被“固定”在屏幕顶部,所以当我在 View Controller 中向下滚动时,Label 始终位于屏幕顶部。

我想要的是让标签在我向下滚动时消失并在我向上滚动时重新出现。我根本不希望标签滚动。我希望它的位置完全固定。

我找到了this answer,但我无法识别 Xcode 8.2.1 中的屏幕截图。

这是视图控制器结构:

【问题讨论】:

  • 你的 ViewController 结构是什么?您可以发布您的故事板的屏幕截图吗?
  • @LordOfLasgalen 请参阅编辑。

标签: ios swift position uilabel


【解决方案1】:

试试这个:

@interface ViewController () <UIScrollViewDelegate>

@property (nonatomic, weak) IBOutlet UILabel *fadingLabel;

@end

@implementation ViewController

#pragma mark - UIScrollViewDelegate

/* For this method to get called, make sure you set the delegate of your table view to this view controller.*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.fadingLabel)
        return;

    CGFloat labelHeight = CGRectGetHeight(self.fadingLabel.frame);
    CGFloat alpha = 1.0f - (scrollView.contentOffset.y / labelHeight);
    [self.fadingLabel setAlpha:alpha];
}

@end

这里是快速翻译:

class ViewController: UIViewController, UIScrollViewDelegate {
    private weak var fadingLabel: UILabel?

    // MARK: - UIScrollViewDelegate

    /* For this method to get called, make sure you set the delegate of your table view to this view controller.*/
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let label = self.fadingLabel else {
            return
        }

        let labelHeight: CGFloat = label.frame.height
        let alpha: CGFloat = 1.0 - (scrollView.contentOffset.y / labelHeight)
        label.alpha = alpha
    }
}

【讨论】:

  • 另外,如果您想在用户滚动时对标签产生较慢的淡出效果,请将labelHeight 乘以一个数字。像:CGFloat labelHeight = CGRectGetHeight(self.fadingLabel.frame) * 2.0f; // or 3.0f 这样可以减缓标签上的褪色效果。
  • 我的 Xcode 项目使用 Swift 3。我已经尝试过 this tool,但我仍然很难让这段代码在 Swift 中编译而没有错误。任何帮助表示赞赏。
【解决方案2】:

您应该实现UIScrollViewDelegate 并根据scrollViewDidScroll(_:) 中滚动视图的垂直内容偏移量隐藏/显示标签。

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    label.isHidden = scrollView.contentOffset.y > 50
}

不要忘记设置滚动视图的委托:

scrollView.delegate = self

【讨论】:

  • 这几乎是完美的。问题是当我向下滚动一点时,标签的位置保持不变,这有点“不切实际”。我更喜欢标签实际上是视图控制器的“一部分”,所以当你向下滚动时,标签自然会从视图中滑出,而不是突然被隐藏。
  • @Crickets 也许this 回答会有所帮助。
猜你喜欢
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多