swift - 基于复杂图像的按钮布局

标签 swift image button layout

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

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

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

最佳答案

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

这是一个简单的示例。

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) {

    }

关于swift - 基于复杂图像的按钮布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262800/

相关文章:

django - 如何在 Django 中处理动态图像?

swift - ios 11 自定义导航栏位于状态栏下方

ios - 如何在 iOS 中将数据发送到蓝牙 LE

ios - 动画阵列不动画 Sprite

android - com.android.camera.action.CROP 调整裁剪矩形的大小

c++ - 将图片从excel复制到剪贴板->在程序中输出->得到平滑的图片。失败在哪里?

android - 我的简单 Android 应用程序在递增整数时崩溃

javascript - JQuery中如何改变按钮文本

iphone - 主屏幕上的 "X"删除按钮是SDK的一部分吗?

ios - 如何在滚动时隐藏导航栏(除非位于屏幕顶部)