【问题标题】:UIView doesn't center properly in UIScrollView with autolayoutUIView 无法在具有自动布局的 UIScrollView 中正确居中
【发布时间】:2015-10-21 10:50:11
【问题描述】:

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

第一个视图在 ScrollView 中居中

第二个视图是错误的,中间有很多空间

在此处查看我的 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 设置图片:

【问题讨论】:

  • @BadalShah 我已经尝试了建议代码来覆盖滚动视图contentOffset,但结果相同。
  • 如何以编程方式或通过情节提要设置滚动视图?你能告诉我你在故事板中的约束吗?
  • @BadalShah 通过情节提要,查看更新

标签: ios swift uiview uiscrollview autolayout


【解决方案1】:

您不应该在viewDidLoad 中执行布局计算,因为在此之前没有正确设置框架。

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

【讨论】:

  • 好点,但与我仍然遇到的问题无关
猜你喜欢
  • 1970-01-01
  • 2016-05-03
  • 2015-04-20
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多