【问题标题】:Centering a Custom Control Programmatically on an AutoLayout View以编程方式在 AutoLayout 视图上居中自定义控件
【发布时间】:2015-11-20 06:58:37
【问题描述】:

每当我执行 HTTP 请求时,我都会将此控件用作活动指示器

https://github.com/gontovnik/DGActivityIndicatorView

我是这样称呼它的

    let activityIndicator: DGActivityIndicatorView = DGActivityIndicatorView();
    activityIndicator.backgroundColor = UIColor.clearColor();
    activityIndicator.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height);
    activityIndicator.size = 68;
    activityIndicator.tintColor = tintColor;
    //activityIndicator.type = DGActivityIndicatorAnimationType.BallClipRotatePulse;
    activityIndicator.startAnimating();

    view.addSubview(activityIndicator);

我在 viewDidLoad 上调用它以及我的 HTTP 请求代码。

但是,这会导致 activityIndi​​cator 位置不在中心,因为在 viewDidLoad 中,自动布局还没有完成布局。

我可以通过将代码放在viewDidAppear 上来解决这个问题,并且activityIndi​​cator 将被正确定位。

但这很糟糕,因为 HTTP 请求只会在 viewDidAppear 上发出,这会浪费一秒钟的宝贵时间。

我应该如何修改控件以使其自行居中?

这个控件是用我不熟悉的Obj-C编码的DGActivityIndicatorView

【问题讨论】:

    标签: ios objective-c uiview


    【解决方案1】:

    要将视图放在另一个视图的中心,请使用以下代码:

    activityIndicator.center = self.view.center;
    

    另外,您可以为activityIndicator 创建一个全局属性。然后您可以在viewDidLoad 中启动HTTP Request 并在viewDidAppear 中写入上述行以使activityIndicator 居中。

    【讨论】:

      【解决方案2】:

      试试这个:

      activityIndicator.center = CGPointMake(view.frame.size.width  / 2, 
                                   view.frame.size.height / 2);
      

      【讨论】:

        【解决方案3】:

        试试这个:

        activityIndicator.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(activityIndicator)
        
        let xCenterConstraint = NSLayoutConstraint(item: activityIndicator, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)
        self.view..addConstraint(xCenterConstraint)
        
        let yCenterConstraint = NSLayoutConstraint(item: activityIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: self.view., attribute: .CenterY, multiplier: 1, constant: 0)
        self.view..addConstraint(yCenterConstraint)
        

        【讨论】:

          【解决方案4】:

          找到了一种在控件本身内执行此操作的方法

          - (void)layoutSubviews {
              [super layoutSubviews];
          
              if (self.layer.sublayers != nil) {
                  self.frame = self.superview.frame;
                  self.layer.position = (CGPoint){CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)};
                  self.layer.sublayers[0].position = (CGPoint){CGRectGetMidX(self.layer.bounds), CGRectGetMidY(self.layer.bounds)};
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-06-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-07-12
            • 2013-09-28
            • 1970-01-01
            相关资源
            最近更新 更多