【问题标题】:Swift Navigationbar and view background colorSwift 导航栏和视图背景颜色
【发布时间】:2016-05-04 20:26:45
【问题描述】:

我正在尝试创建一个应用程序,其中 UINavigationBar 和 UIView 的背景颜色相同。

这就是我所做的:

  • 已创建 customUINavigationBar(继承自 UINavigationBar)
  • 创建 customUIView(继承自 UIView)

然后我将以下代码添加到customUINavigationBar

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    self.backgroundColor = Colors.turquoise
    let attributes = [NSFontAttributeName: UIFont(name: "AppleGothic", size: 20)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
    self.titleTextAttributes = attributes

    for parent in self.subviews {
        for child in parent.subviews {
            if child is UIImageView {
                child.removeFromSuperview()
            }
        }
    }
}

我还尝试将 self.barTintColor = Colors.turquoiseself.tintColor = Colors.turquoise 添加到 init 函数中,但这不会改变结果。

在我的customUIView 课程中,我有以下代码:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    self.backgroundColor = Colors.turquoise
}

Colors.turquoise 来自一个包含这行代码的自定义类:

static var turquoise = UIColor(red: 132/255, green: 217/255, blue: 217/255, alpha: 1.0)

以上代码的结果如截图所示。如您所见,导航栏和视图之间的颜色略有不同。如何在导航栏和视图中获得相同的颜色而不会有任何差异?

提前致谢!

【问题讨论】:

  • 你试过 self.translucent = false; self.opaque = true 在您所需的 init?(coder aDecoder: NSCoder) 方法中?
  • 刚刚尝试过,根据您的建议(也将半透明更改为真)会提供更暗的导航栏

标签: ios swift uiview uinavigationbar


【解决方案1】:

为您的颜色“132.f/255.f green:217.f/255.f blue:217.f/255.f”使用浮点值

我在objective-c中创建了相同的UINavigationBar子类:

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.translucent = NO;
        self.opaque = YES;
        self.barTintColor = [UIColor colorWithRed:132.f/255.f green:217.f/255.f blue:217.f/255.f alpha:1.0];
    }
    return  self;
}

它按预期工作:

【讨论】:

  • 感谢您的回答,但是当我将 UIColor 更改为使用例如 217.f/255.f 时,我收到“'Int' 类型的值没有成员 'f'”错误。
  • 就这样用 UIColor (red: 132.0/255.0, green: 217.0/255.0, blue: 217.0/255.0, alpha: 1.0)
  • 很抱歉没有时间早点尝试,但它成功了!感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-08-12
  • 2015-04-18
  • 2015-07-22
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多