我对编程很新,我正试图弄清楚如何在复杂的布局中创建多个按钮。我的布局基本上是一个透明的PNG,一个切成24个部分的身体,我希望身体的每个部分都是一个单独的按钮。
我在视图控制器中尝试了一些布局。设置大量按钮覆盖图像(在模拟器中启动时无法保持布局直线)我尝试给出按钮图像,我尝试过大图像尺寸的按钮,但我只能使用最顶部的按钮
有没有办法做到这一点,还是需要代码可行?
答案 0 :(得分:0)
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) {
}