【问题标题】:Adding a custom UIBarButtonItem to a UINavigationBar将自定义 UIBarButtonItem 添加到 UINavigationBar
【发布时间】:2016-08-27 21:40:12
【问题描述】:

我试图将一个大的加号按钮作为右栏按钮,下面的代码在故事板中工作,但是在将所有内容移动到 xib 文件和单独的 .swift 文件之后,这是唯一坏的东西。

let button = UIButton(type: .Custom)
button.setTitle("+", forState: .Normal)
button.titleLabel?.font = UIFont.systemFontOfSize(20.0)
button.frame = CGRectMake(0, 0, 100, 40)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: .Plain, target: self, action: #selector(GroupNavViewController.onCreate))
self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(40)], forState: .Normal)

UINavigationController 是它自己的 .swift 文件,没有 xib 文件。

我不知道为什么它在情节提要中起作用,但现在不起作用。

理想情况下,我想要一个大的加号按钮(因为正常的字体大小似乎有点太小了)

【问题讨论】:

标签: ios swift button uinavigationcontroller uibarbuttonitem


【解决方案1】:

UINavigationController 是它自己的 .swift 文件,没有 xib 文件。

在 UIViewController 类中而不是在您的 UINavigationController 中创建此按钮。因此,将相同的代码移至您的 UIViewController。

【讨论】:

  • 那行不通,标题也不这样显示
【解决方案2】:

对我有用。我刚刚摆脱了目标行动,所以我不必实施它。全部在代码中完成。没有故事板,也没有 xib。

AppDelegate.swift

var window: UIWindow?
let viewController = ViewController();

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let navigationController = UINavigationController(rootViewController:viewController)

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window!.backgroundColor = UIColor.whiteColor()
    self.window!.rootViewController = navigationController
    self.window!.makeKeyAndVisible()

    return true
}

ViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(type: .Custom)
    button.setTitle("+", forState: .Normal)
    button.titleLabel?.font = UIFont.systemFontOfSize(20.0)
    button.frame = CGRectMake(0, 0, 100, 40)

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "+", style: .Plain, target: self, action: nil)
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(40)], forState: .Normal)

}

【讨论】:

  • 这行得通,谢谢。我试图将按钮添加到导航控制器,而不是它包含的视图控制器。
猜你喜欢
  • 2015-12-01
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多