Я создаю приложение Swift с панелью инструментов внизу. Я создал панель инструментов с представлением коллекции, потому что я следовал инструкции: давайте создадим это приложение на YouTube: https://www.youtube.com/channel/UCuP2vJ6kRutQBfRmdcI92mA
Но с панелью инструментов я столкнулся с проблемой. Когда я создаю новый вид на контроллере представления, панель инструментов также не выдвигается. Как я прочитал, это связано с тем, что созданная мной панель инструментов связана с контроллером, от которого я только что избавился, и теперь навигационный контроллер обрабатывает выдвинутый вид. Я также читал, что если я добавлю панель инструментов через:
navigationController?.isToolbarHidden = false
, то при нажатии на новый контроллер элементы будут отсутствовать. К сожалению, я больше не могу найти ссылку (это было где-то здесь, на StackOverflow) ...
Поэтому я хотел знать, есть ли возможность добавить новый контроллер pu sh и заставить панель инструментов остаться. Может быть, что-то вроде добавления панели инструментов и элементов в контроллер навигации.
Код, который я написал, выглядит следующим образом:
Панель инструментов
class ToolbarMenu: UIView, UICollectionViewDataSource, UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout {
//Nachschauen warum das geht?
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .standardColor
cv.dataSource = self
cv.delegate = self
return cv
}()
let cellId = VerticalCell.Toolbar.rawValue
let imageNames = ["Home", "Ball", "Table", "Account"]
let cellNames = ["Home", "Games", "Table", "Account"]
var horizontalBarLeftAnchorConstraint: NSLayoutConstraint?
var homeController: HomeController?
override init(frame: CGRect) {
super.init(frame: frame)
collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)
addSubview(collectionView)
addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView)
addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView)
//Preselected State
let selectedIndexPath = IndexPath(item: 0, section: 0)
collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: .top)
setupHorizontalBar()
}
func setupHorizontalBar(){
let horizontalBarView = UIView()
horizontalBarView.backgroundColor = UIColor(white: 0.9, alpha: 1)
horizontalBarView.translatesAutoresizingMaskIntoConstraints = false
addSubview(horizontalBarView)
horizontalBarLeftAnchorConstraint = horizontalBarView.leftAnchor.constraint(equalTo: self.leftAnchor)
horizontalBarLeftAnchorConstraint?.isActive = true
horizontalBarView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
horizontalBarView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1/4).isActive = true
horizontalBarView.heightAnchor.constraint(equalToConstant: 3).isActive = true
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
homeController?.scrollToMenuIndex(menuIndex: indexPath.item)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuCell
cell.imageView.image = UIImage(named: imageNames[indexPath.item])?.withRenderingMode(.alwaysTemplate)
cell.cellLabel.text = cellNames[indexPath.item]
cell.tintColor = .black
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: frame.width / 4, height: frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
MenuCell
class MenuCell: BaseCell {
let imageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "Ball")?.withRenderingMode(.alwaysTemplate)
iv.tintColor = .black
return iv
}()
let cellLabel: UILabel = {
let cellLabel = UILabel()
cellLabel.translatesAutoresizingMaskIntoConstraints = false
cellLabel.font = .standardText(size: 14)
cellLabel.textAlignment = .center
return cellLabel
}()
override var isHighlighted: Bool {
didSet {
imageView.tintColor = isHighlighted ? UIColor.white : .black
}
}
override var isSelected: Bool {
didSet {
imageView.tintColor = isSelected ? UIColor.white : .black
}
}
override func setupViews() {
super.setupViews()
addSubview(imageView)
addSubview(cellLabel)
addConstraintsWithFormat(format: "H:[v0(28)]", views: imageView)
addConstraintsWithFormat(format: "V:[v0(28)]-3-[v1(15)]", views: imageView, cellLabel)
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: -10))
addConstraint(NSLayoutConstraint(item: cellLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
}
}
Добавление панели инструментов в Homecontroller
view.addSubview(toolBar)
view.addConstraintsWithFormat(format: "H:|[v0]|", views: toolBar)
view.addConstraintsWithFormat(format: "V:[v0(60)]-40-|", views: toolBar)
HomeController:
let layout = UICollectionViewFlowLayout()
let vc = newController(collectionViewLayout: layout)
vc.cellFixture = fixture
navigationController?.pushViewController(vc, animated: true)
Также: Если у кого-то есть комментарии о том, как улучшить мой кодирование, я рад это слышать :)