【问题标题】:Why does my UIView got different position on different iPhones?为什么我的 UIView 在不同的 iPhone 上的位置不同?
【发布时间】:2016-04-26 19:15:31
【问题描述】:

为什么我的UIView 在不同的 iPhone 屏幕尺寸上有不同的位置?我想这是因为autoresizingMask,但是在应用autoresizingMask 之后我怎么能得到一个视图框架来创建一些通用逻辑呢?或者处理这个问题的最佳做法是什么?

这里是代码:

private func setup() {

        positionView = CircularProjectPositionControl(frame: self.bounds)
        positionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        positionView.outerCircleWidth = outerCircleWidth

        assetsView = CircularProjectAssetsControl(frame: self.bounds)
        assetsView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        assetsView.backgroundColor = UIColor.clearColor()
        assetsView.imageWidth = outerCircleWidth

        let size = CGSize(width:40, height:40)
        let width = floor(CGRectGetMidX(self.bounds) - size.width/2.0)
        let height = floor(CGRectGetMidY(self.bounds) - size.width/2.0)
        collaboratorView = AvatarView(frame: CGRect(x: width, y: height, width: size.width, height: size.height))
        collaboratorView.autoresizingMask = [.FlexibleBottomMargin, .FlexibleLeftMargin, .FlexibleRightMargin]

        self.addSubview(assetsView)
        self.addSubview(positionView)
        self.addSubview(collaboratorView)
    }

iPhone 6s:

iPhone 5:

【问题讨论】:

  • 为什么要以编程方式执行此操作?在 Storyboard 中使用自动布局约束会更容易
  • @matt.writes.code 我不能在这里使用故事板

标签: swift autolayout autoresizingmask


【解决方案1】:

尝试添加 .CenterX.CenterY 约束以使每个子视图居中:

NSLayoutConstraint(item: view1, attribute: .CenterX, relatedBy: .Equal, toItem: view2, attribute: .CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: view1, attribute: .CenterY, relatedBy: .Equal, toItem: view2, attribute: .CenterY, multiplier: 1, constant: 0).active = true

【讨论】:

    【解决方案2】:

    看起来你只设置了 self.view 的相对位置。如果你想让三个圆有一些保持相同的相对位置,你还应该设置它们之间的约束。

    【讨论】:

    • 那么我应该添加自动布局约束还是 autoresizingMask 掩码?
    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多