总的来说,我对编程相当陌生,我正在尝试弄清楚如何在复杂的布局中创建大量按钮。我的布局基本上是一个透明的 PNG 主体,切成大约 24 个部分,我希望主体的每个部分都是一个单独的按钮。
我在 View Controller 中尝试了一些布局。设置大量按钮覆盖图像(在模拟器中启动时无法保持布局直线)并且我尝试提供按钮图像,我尝试过大图像大小的按钮,但我只能使用最上面的按钮.
有什么办法可以做到这一点,还是需要代码才能实现?
最佳答案
UICollectionViewController
或 UICollectionView
是您更好的选择。您可以设置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/