UIView没有在UIScrollView中使用autolayout正确居中

时间:2015-10-21 10:50:12

标签: ios swift uiview uiscrollview autolayout

我正在制作一个应用程序,我需要x个自定义UIView并将其放在scrollView中。 scrollViewUIView xib的布局设置为AutoLayout。我现在得到的结果是:

First View is well centred in ScrollView First View在ScrollView中居中

Second View is wrong and has a lot of space in between 第二个视图错误,并且在

之间有很大的空间

请在此处查看我的VC代码。

let sponsors = Sponsors.createSponsors() <-- Array

override func viewDidLoad() {
    super.viewDidLoad()

    configureSponsors()
}

//MARK: Load the AddView in ScrollView
func configureSponsors() {

    self.scrollView.contentSize = CGSizeMake(CGFloat(sponsors.count) * self.scrollView.frame.size.width, self.scrollView.frame.size.height)

    for sponsor in sponsors {

        numberOfItems++

        let addView = NSBundle.mainBundle().loadNibNamed("AddView", owner: self, options: nil).last as! AddView
        addView.addDataToAddView(sponsor)
        addView.frame = CGRectMake(CGFloat(numberOfItems - 1) * scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)

        self.scrollView.addSubview(addView)
    }
}

这是我的UIView代码:

//MARK: Outlets
@IBOutlet weak var backgroundImageView: UIImageView!

@IBOutlet weak var sponsorTitle: UILabel!
@IBOutlet weak var sponsorLogo: UIImageView!
@IBOutlet weak var sponsorSubtitle: UILabel!

@IBOutlet weak var roundView: UIView!
@IBOutlet weak var playMusicButton: UIButton!

//MARK: Properties
var cornerRadius: CGFloat = 3.0

func addDataToAddView(sponsor: Sponsors) {

    backgroundImageView.image = UIImage(named: sponsor.backgroundImage)
    sponsorLogo.image = UIImage(named: sponsor.logoImage)
    sponsorTitle.text = sponsor.title
    sponsorSubtitle.text = sponsor.subTitle
}

override func layoutSubviews() {

    roundView.layer.cornerRadius = roundView.frame.size.width / 2
    roundView.alpha = 0.7
    roundView.clipsToBounds = true
}

//MARK: PlayVideo
@IBAction func playVideo(sender: UIButton) {
    //play music
}

我已经搜索过同样的问题了。我发现我必须使用Pure Auto Layout Approach。这是否意味着我需要以编程方式为UIView设置约束? 非常感谢,

达克斯

更新

scrollView设置的图片:

Attributes Inspector Size Inspector

1 个答案:

答案 0 :(得分:0)

您不应在viewDidLoad中执行布局计算,因为此时帧设置不正确。

执行此操作的正确位置可以是viewWillLayoutSubviewsviewDidLayoutSubviews,因为在调用这些函数时您将获得正确的帧数据