如何制作水平滚动视图和其中的一些按钮(编程)

2024-05-07

抱歉,我有一个问题。我不使用 StoryBoard。

我想做一个这样的视图。
照片由 terence Luffy/AppStore 拍摄 风格 Horizo​​ntalScrollView https://camo.githubusercontent.com/981c03a8c109b8649e54a154d6478b44c9b44e89/68747470733a2f2f646c2e64726f70626f7875736572636f6e74656e742e636f6d2f752f39313637353332332f7468756d626f6f6b72312e676966

but I try to do this. Finlly,scrollView just show last button like this. enter image description here

这是代码:

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)

}

请帮我。 谢谢大家!


有两种方法可以实现它:)一种是使用scrollView并计算偏移量并以编程方式在ScrollView上设置视图作为子视图的困难方法,否则使用集合视图

Step 1:

将 UICollectionView 添加到 Storyboard,设置 collectionView 的高度以满足您的要求:)

Step 2

创建一个单元格,其大小取决于您的要求。我创建了一个背景颜色为橙色/粉色的单元格。在其上添加标签以显示您的号码。

Step 3:

将可重用单元标识符设置为单元并设置其类:)

Step 4 :

将 collectionView 滚动方向设置为水平:)

Step 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;
    }
}

就这样 :)

最终输出

使用单元格 ABCD 查看 collectionView :D

附加信息

如果您在 UIViewController 上拖动 collectionView,您可能会发现 collectionView 在顶部留下了一个间隙,您可以通过取消选中调整 ViewController 的 ScrollView Insets 来解决这个问题:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何制作水平滚动视图和其中的一些按钮(编程) 的相关文章

随机推荐