Swift 自定义导航项
Swift Custom navigation Item
我想在我的代码中创建一个自定义的左侧导航栏按钮。
我可以用标题或只有图像来做。
当我同时想要用户标题和图像时,按钮看起来不合适。
我尝试添加两个按钮。一个用于标题,另一个用于图像,但这次按钮之间的 space 太多了。
我想要像这样的左导航按钮:
如何将左栏按钮项目设置为图像? (<聊天部分)
首先,创建一个带有标题和图像的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
然后,使用 imageEdgeInsets
和 titleEdgeInsets
调整 uibutton 中标题和图像的位置:
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);
这里调整insets有点技术含量,我只是提供一个答案,你可以直接使用。有关详细信息,请查看此 post Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets
问题是您没有正确设置按钮的 imageEdgeInset 和 titleEdgeInset,这就是为什么您在标题和图像之间得到更多 space 尝试设置按钮的 imageEdgeInset 和 titleEdgeInset:
leftBarBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5)
leftBarBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
我想在我的代码中创建一个自定义的左侧导航栏按钮。 我可以用标题或只有图像来做。 当我同时想要用户标题和图像时,按钮看起来不合适。
我尝试添加两个按钮。一个用于标题,另一个用于图像,但这次按钮之间的 space 太多了。
我想要像这样的左导航按钮:
如何将左栏按钮项目设置为图像? (<聊天部分)
首先,创建一个带有标题和图像的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
然后,使用 imageEdgeInsets
和 titleEdgeInsets
调整 uibutton 中标题和图像的位置:
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);
这里调整insets有点技术含量,我只是提供一个答案,你可以直接使用。有关详细信息,请查看此 post Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets
问题是您没有正确设置按钮的 imageEdgeInset 和 titleEdgeInset,这就是为什么您在标题和图像之间得到更多 space 尝试设置按钮的 imageEdgeInset 和 titleEdgeInset:
leftBarBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5)
leftBarBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)