1 iphone uiscrollview horizontal-scrolling ios swift
对不起,我有问题.我不使用storyBoard.
我想这样看.
照片来自terenceLuffy/AppStoreStyleHorizontalScrollView
但我试着这样做.Finlly,scrollView只显示这样的最后一个按钮.
这是代码:
var scView:UIScrollView = UIScrollView()
var buttonPadding:CGFloat = 10
var xOffset:CGFloat = 10
scView.backgroundColor = UIColor.blue
scView.translatesAutoresizingMaskIntoConstraints = false
func viewDidLoad() {
for i in 0 ... 10 {
let button = UIButton()
button.tag = i
button.backgroundColor = UIColor.darkGray
button.setTitle("\(i)", for: .normal)
button.addTarget(self, action: #selector(btnTouch), for: UIControlEvents.touchUpInside)
button.frame = CGRect(x: xOffset, y: CGFloat(buttonPadding), width: 70, height: 30)
xOffset = xOffset + CGFloat(buttonPadding) + button.frame.size.width
scView.addSubview(button)
}
scView.contentSize = CGSize(width: xOffset, height: scView.frame.height)
}
Run Code Online (Sandbox Code Playgroud)
请帮我.谢谢大家!
San*_*ari 10
实现它的方法有两种:一种是使用scrollView并在ScrollView上以编程方式计算偏移量和设置视图的一种方法,因为subView使用CollectionView
步骤1:
在故事板中添加UICollectionView,设置collectionView的高度以符合您的要求:)
第2步
创建一个单元格,其大小取决于您的要求.我创建了一个背景颜色为橙色/粉红色的单元格.在其上添加了标签以显示您的号码.
第3步:
将可重用的单元标识符设置为单元格并设置其类:)
第4步 :
将collectionView滚动方向设置为水平:)
第5步:
现在实现collectionView委托和数据源方法:)
extension ViewController : UICollectionViewDataSource,UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
cell.myLabel.text = "ABCD"
return cell;
}
}
Run Code Online (Sandbox Code Playgroud)
就这样 :)
最终的O/P.
查看带有单元格ABCD的collectionView:D
附加信息
如果你在UIViewController上拖动一个collectionView,你可能会看到collectionView在顶部留下了一个空隙,您可以通过取消选中调整ScrollView的ViewController Insets来解决这个问题.
我已经尝试过你的代码并对其进行了一些更改。它会按预期工作,除非您有其他情况发生:
var scView:UIScrollView!
let buttonPadding:CGFloat = 10
var xOffset:CGFloat = 10
override func viewDidLoad() {
super.viewDidLoad()
scView = UIScrollView(frame: CGRect(x: 0, y: 120, width: view.bounds.width, height: 50))
view.addSubview(scView)
scView.backgroundColor = UIColor.blue
scView.translatesAutoresizingMaskIntoConstraints = false
for i in 0 ... 10 {
let button = UIButton()
button.tag = i
button.backgroundColor = UIColor.darkGray
button.setTitle("\(i)", for: .normal)
//button.addTarget(self, action: #selector(btnTouch), for: UIControlEvents.touchUpInside)
button.frame = CGRect(x: xOffset, y: CGFloat(buttonPadding), width: 70, height: 30)
xOffset = xOffset + CGFloat(buttonPadding) + button.frame.size.width
scView.addSubview(button)
}
scView.contentSize = CGSize(width: xOffset, height: scView.frame.height)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15417 次 |
最近记录: |