如何为 UITabBar 项目之一添加左右边框?
How can I add left and right borders for one of the UITabBar items?
如果您查看下图,您会看到两条竖线 -- 分隔中间的选项卡项。 (线条模糊)
在代码中,如何创建这两行?
您可以:
1. 在 .png
中添加带有线条的选定图像
2. 设置带线条的背景图像并根据所选选项卡更改此图像。
3. 创建自己的视图,继承自 UIView
并将其添加为子视图(在这种情况下,您必须实现自己的切换逻辑)
This will help you to add the seperators
//Add seperators Line
if let items = self.tabBar.items {
//Get the height of the tab bar
let height = self.tabBar.bounds.height
let width = self.tabBar.bounds.width
//Calculate the size of the items
let numItems = CGFloat(items.count)
let itemSize = CGSize(
width: tabBar.frame.width / numItems,
height: tabBar.frame.height)
for (index, _) in items.enumerated() {
//We don't want a separator on the left of the first item.
if index > 0 {
//Xposition of the item
let xPosition = itemSize.width * CGFloat(index)
let separator = UIView(frame: CGRect(
x: xPosition, y: 0, width: 3.5, height: height))
separator.backgroundColor = UIColor.white
tabBar.insertSubview(separator, at: 1)
}
}
扩展 UIImage {
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
如果您查看下图,您会看到两条竖线 -- 分隔中间的选项卡项。 (线条模糊)
在代码中,如何创建这两行?
您可以:
1. 在 .png
中添加带有线条的选定图像
2. 设置带线条的背景图像并根据所选选项卡更改此图像。
3. 创建自己的视图,继承自 UIView
并将其添加为子视图(在这种情况下,您必须实现自己的切换逻辑)
This will help you to add the seperators
//Add seperators Line
if let items = self.tabBar.items {
//Get the height of the tab bar
let height = self.tabBar.bounds.height
let width = self.tabBar.bounds.width
//Calculate the size of the items
let numItems = CGFloat(items.count)
let itemSize = CGSize(
width: tabBar.frame.width / numItems,
height: tabBar.frame.height)
for (index, _) in items.enumerated() {
//We don't want a separator on the left of the first item.
if index > 0 {
//Xposition of the item
let xPosition = itemSize.width * CGFloat(index)
let separator = UIView(frame: CGRect(
x: xPosition, y: 0, width: 3.5, height: height))
separator.backgroundColor = UIColor.white
tabBar.insertSubview(separator, at: 1)
}
}
扩展 UIImage {
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}