代码之家  ›  专栏  ›  技术社区  ›  Crickets

如何固定UILabel位置?

  •  0
  • Crickets  · 技术社区  · 6 年前

    我在Xcode的界面生成器中将一个“标签”对象拖到情节提要中的场景中。

    问题是标签“固定”在屏幕顶部,因此当我在视图控制器中向下滚动时,标签始终位于屏幕顶部。

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

    我发现 this answer 但我不认识Xcode 8.2.1中的屏幕截图。

    以下是视图控制器结构:

    image

    2 回复  |  直到 6 年前
        1
  •  1
  •   Pranay    6 年前

    尝试以下操作:

    @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
        }
    }
    
        2
  •  0
  •   Tamás Sengel RIJO JOSEPH    6 年前

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

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

    不要忘记设置滚动视图的代理:

    scrollView.delegate = self