昨天使用swift写一个cell时,使用pagecontrol,在设其frame想让其居中,使用两个方法
设原点x坐标为WXDevice.width/2 - pageWidth/2
设pagecontrol 原点点x=0,width = WXDevice.width
但结果两种方法都有问题(5S中却显示居中),pagecontrol 位置总有偏移,最后的解决方法是,在layoutSubviews方法里设置,其frme
override func layoutSubviews() {
super.layoutSubviews()
self.pageControl.frame = CGRectMake(0, vHeight - 10, deviceWidth, 20)
}
问题就解决了,大概的原因,是这样的,当开始设置frame时,上面两个方法设的位置的确是居中,只是设备默认一开始,以320为设备宽度,所以当实际设备的宽度不是320时,进行重新布局时,就会出现这个问题。这也是为什么5s显示居中的原因。
self.likeScrollView = UIScrollView()
self.likeScrollView.frame = CGRectMake(CGFloat(0), 0, deviceWidth, CGFloat( vHeight))
self.likeScrollView.showsHorizontalScrollIndicator = false //去掉默认水平滑动条
self.likeScrollView.pagingEnabled = true // 翻页属性
self.likeScrollView.contentSize = CGSizeMake(deviceWidth * CGFloat(pageCount), CGFloat(self.likeScrollView.frame.size.height))
self.likeScrollView.delegate = self
self.contentView.addSubview(self.likeScrollView)
//for 添加每页的view
for (var i = 0 ; i < pageCount; i++) {
var v: UIView = UIView(frame: CGRectMake(CGFloat(i) * deviceWidth, self.titleLB.frame.size.height, deviceWidth, self.likeScrollView.frame.size.height))
self.likeScrollView.addSubview(v)
}
self.pageControl = UIPageControl()
self.pageControl.numberOfPages = pageCount;
self.pageControl.pageIndicatorTintColor = UIColor.grayColor()// 设置非选中页的圆点颜色
self.pageControl.pageIndicatorTintColor = UIColor(red: 204/255.0, green: 204/255.0, blue: 204/255.0, alpha: 0.5) // #cccccc
self.pageControl.currentPageIndicatorTintColor = UIColor.redColor()// 设置选中页的圆点颜色
self.pageControl.currentPageIndicatorTintColor = UIColor(red: 225/255.0, green: 22/255.0, blue: 68/255.0, alpha: 1) // #e11644
self.pageControl.enabled = false // 禁止默认的点击功能
self.pageControl.backgroundColor = UIColor.clearColor()
self.pageControl.currentPage = 0
self.contentView.addSubview(self.pageControl)
override func layoutSubviews() {
super.layoutSubviews()
self.pageControl.frame = CGRectMake(0, vHeight - 10, deviceWidth, 20)
}
//滑动切换
func scrollViewDidScroll(scrollView: UIScrollView) {
var pageWidth:CGFloat = scrollView.frame.size.width;
var page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = Int( page)
}