Stackview в панели навигации - PullRequest
0 голосов
/ 24 апреля 2018

Можно ли программно разместить UIStackView в NavigationBar с помощью swift?Я хочу разместить там StackView с двумя расположенными стеками.Но когда я это делаю, в навигационной панели ничего не отображается.Если это возможно, приведите пример.Спасибо

Ответы [ 2 ]

0 голосов
/ 24 апреля 2018

Вы можете сделать любой UIView подкласс (из которых UIStackView - один) заголовок панели навигации, используя свойство navigationItem.titleView вашего контроллера представления.

Вы можете проверить это на детской площадке ...

import UIKit
import PlaygroundSupport

let vc = UIViewController()
vc.view.backgroundColor = .white
let nav = UINavigationController(rootViewController: vc)

let topLabel = UILabel()
topLabel.font = UIFont.boldSystemFont(ofSize: 20)
topLabel.text = "Hello"

let bottomLabel = UILabel()
bottomLabel.font = UIFont.systemFont(ofSize: 16)
bottomLabel.text = "World!"

let stackView = UIStackView(arrangedSubviews: [topLabel, bottomLabel])
stackView.axis = .vertical

vc.navigationItem.titleView = stackView

PlaygroundPage.current.liveView = nav.view
PlaygroundPage.current.needsIndefiniteExecution = true

enter image description here

0 голосов
/ 24 апреля 2018

Наконец я нашел решение

let btnSort   = UIButton(type: .system)
    btnSort.frame =  CGRect(x: 0, y: 0, width: 120, height: 40)
    btnSort.tintColor = UIColor.white
    btnSort.setImage(UIImage(named:"ic_controls_icon.png"), for: .normal)
    btnSort.imageEdgeInsets = UIEdgeInsets(top: 6,left: -10,bottom: 6,right: 34)
    btnSort.titleEdgeInsets = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 14)
    btnSort.setTitle("SORT", for: .normal)
    btnSort.layer.borderWidth = 1.0
    btnSort.backgroundColor = UIColor.red //--> set the background color and check
    btnSort.layer.borderColor = UIColor.white.cgColor

    let btnControl   = UIButton(type: .system)
    btnControl.frame =  CGRect(x: 0, y: 0, width: 120, height: 40)
    btnControl.tintColor = UIColor.white
    btnControl.setImage(UIImage(named:"ic_controls_icon.png"), for: .normal)
    btnControl.imageEdgeInsets = UIEdgeInsets(top: 6,left: -10,bottom: 6,right: 34)
    btnControl.titleEdgeInsets = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 14)
    btnControl.setTitle("SORT", for: .normal)
    btnControl.layer.borderWidth = 1.0
    btnControl.backgroundColor = UIColor.red //--> set the background color and check
    btnControl.layer.borderColor = UIColor.white.cgColor

    let view = UIStackView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
    view.axis = .horizontal
    view.distribution = .fillEqually
    view.spacing = 5
    view.addArrangedSubview(btnSort)
    view.addArrangedSubview(btnControl)

    let mainTitleView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
    mainTitleView.addSubview(view)


    navigationItem.titleView = mainTitleView
...