Ios UIView在带有autolayout的UIScrollView中无法正确居中
我正在制作一个应用程序,其中需要x数量的自定义UIView,并将它们放置在scrollView中。scrollView和UIView xib的布局使用AutoLayout设置。我现在得到的结果是: 第一个视图在ScrollView中居中 第二种观点是错误的,两者之间有很大的空间 看看我的VC代码在这里Ios UIView在带有autolayout的UIScrollView中无法正确居中,ios,swift,uiview,uiscrollview,autolayout,Ios,Swift,Uiview,Uiscrollview,Autolayout,我正在制作一个应用程序,其中需要x数量的自定义UIView,并将它们放置在scrollView中。scrollView和UIView xib的布局使用AutoLayout设置。我现在得到的结果是: 第一个视图在ScrollView中居中 第二种观点是错误的,两者之间有很大的空间 看看我的VC代码在这里 let sponsors = Sponsors.createSponsors() <-- Array override func viewDidLoad() { super.v
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设置约束?
非常感谢,
达克斯
更新:
scrollView设置的图片:
您不应该在viewDidLoad中执行布局计算,因为在此之前帧的设置不正确
正确的做法是viewWillLayoutSubviews或viewDidLayoutSubviews,因为调用这些函数时,您将获得正确的帧数据尝试此@BadalShah我已尝试使用建议代码覆盖scrollViews内容偏移量,但结果相同。如何通过编程或故事板设置scroll view?你能告诉我你在情节提要中的限制吗?@BadalShah通过情节提要,看到updateGood point,但与我仍然遇到的问题无关
//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
}