【问题标题】:Complex Image based Button Layout基于复杂图像的按钮布局
【发布时间】:2017-01-08 19:44:48
【问题描述】:

总的来说,我对编程还很陌生,我正试图弄清楚如何在复杂的布局中创建大量按钮。我的布局基本上是一个透明的 PNG,身体被切割成大约 24 个部分,我希望身体的每个部分都是一个单独的按钮。

我在视图控制器中尝试了一些布局。设置大量按钮覆盖图像(在模拟器中启动时无法保持布局笔直)并且我尝试提供按钮图像,我尝试过大图像大小的按钮,但我只能使用最顶部的按钮.

有什么方法可以做到这一点,还是需要代码才能做到?

【问题讨论】:

    标签: swift image button layout


    【解决方案1】:

    UICollectionViewControllerUICollectionView 是您更好的选择。您可以设置UICollectionViews 背景图片,并将单元格视为您的按钮。

    这是一个简单的例子。

    import UIKit
    
    class Collection: UICollectionViewController {
    
        private let cellId = "cell"
    
        override init(collectionViewLayout layout: UICollectionViewLayout) {
            if let l = layout as? UICollectionViewFlowLayout{
                l.minimumInteritemSpacing = 0
                l.sectionInset = UIEdgeInsetsZero
                l.scrollDirection = .Vertical
                l.footerReferenceSize = CGSize.zero
                l.headerReferenceSize = CGSize.zero
                let screenWidth = UIScreen.mainScreen().bounds.width
                let itemWidth = CGFloat(Int(screenWidth/4))
                l.itemSize = CGSize(width: itemWidth, height: itemWidth)
            }
            super.init(collectionViewLayout: layout)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            view.backgroundColor = UIColor.whiteColor()
            collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    
        }
    
    }
    
    extension Collection{
    
        override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
            return 4
        }
    
        override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 4
        }
    
        override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath)
            cell.backgroundColor = UIColor.redColor()
            return cell
        }
    
    }
    

    如果您想向单元格添加触摸操作。

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        }
    

    【讨论】:

    • 我正在试图弄清楚这段代码,是不是说它需要一张图像并将其分成 4 个象限?
    • 抱歉,我在完成打字之前不小心发送了那个......我不确定这段代码对我的情况有什么帮助,我有一个非常不规则的(人体轮廓)形状。不是很方。有没有办法使用它来将精确的点或矢量形状指定为按钮或 PNG 形状?您发布的代码可能超出了我的想象,我担心我无法弄清楚这一点。或者使用它并将我的图像分成80个这样的块并将一组指定为一个按钮的一部分是最有效的吗?我会发布一张图片,但我不能。
    猜你喜欢
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多