【问题标题】:Swift Custom navigation ItemSwift 自定义导航项
【发布时间】:2016-06-11 16:10:43
【问题描述】:

我想在我的代码中创建一个自定义的左侧导航栏按钮。 我可以用标题或只有图像来做。 当我同时想要用户标题和图像时,按钮看起来不合适。

我尝试添加两个按钮。一个是标题,另一个是图像,但这次按钮之间的空间太大了。

我想要左导航按钮,例如:

我怎样才能像图片一样做左栏按钮项目? (

【问题讨论】:

    标签: swift uinavigationcontroller swift2 uinavigationitem


    【解决方案1】:

    首先,创建一个带有title和image的uibutton,并将navigationbar的leftbuttonitem设置为创建的unbutton:

    //create the uibutton
    var button = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
    //Set the image
    button?.setImage(UIImage(named: "yourImageName.jpg"), forState: UIControlState.Normal)
    //Set the title
    button?.setTitle("Yourtitle", forState: UIControlState.Normal)
    //Add target
    button?.addTarget(self, action:"callMethod", forControlEvents: UIControlEvents.TouchDragInside)
    button?.frame=CGRectMake(0, 0, 30, 30)
    //Create bar button
    var barButton = UIBarButtonItem(customView: button!)
    self.navigationItem.leftBarButtonItem = barButton
    

    然后,使用imageEdgeInsetstitleEdgeInsets调整uibutton内title和image的位置:

    let spacing:CGFloat = 10.0; // the amount of spacing to appear between image and title
    tabBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
    tabBtn.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
    

    这里调整插图有点技术性,我只是提供一个您可以直接使用的答案。欲了解更多信息,请查看此帖子Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

    【讨论】:

      【解决方案2】:

      问题是您没有正确设置按钮的 imageEdgeInset 和 titleEdgeInset 这就是为什么标题和图像之间有更多空间尝试设置按钮的 imageEdgeInset 和 titleEdgeInset:

      leftBarBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5)
      leftBarBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
      

      【讨论】:

        猜你喜欢
        • 2015-07-15
        • 1970-01-01
        • 2017-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-25
        • 1970-01-01
        相关资源
        最近更新 更多