我希望我的应用程序行为如下:
确保我的NavigationItem.titleView的确切行为非常重要
我到目前为止遵循了这些步骤:
我在我的应用程序中以编程方式创建了三个视图:
(1)container
=>保持(2)和(3)=>附加了一个gestureRecognizer
let container = UIView(frame: CGRectMake(0,0,200,40))
(2)imageContainer
=>有图像
let imageContainer = UIImageView(frame: CGRectMake(0, 0, 30, 30))
imageContainer.image = UIImage(named: "mock.jpg")
(3)textContainer
=>有一些文字
let textContainer = UILabel(frame: CGRectMake(0,0, 180, 20))
textContainer.text = "Group xY"
以下我设置图像的中心以对齐它们:
imageContainer.center = CGPointMake(container.frame.size.width / 2,
container.frame.size.height / 2)
textContainer.center = CGPointMake(container.frame.size.width / 2,
container.frame.size.height / 2)
现在我将所有子视图添加到我的视图和设置
self.navigationItem.titleView = (1)
启动应用程序显示,titleView的元素未正确对齐
有没有办法正确实现这种确切的行为?
注意:不要担心圆形图像。我知道如何实现这一点。
答案 0 :(得分:1)
您应该将textContainer的大小设置为更接近文本的边界。您可以通过调用sizeToFit
来执行此操作,然后您需要将imageContainer设置为文本的左侧,这样图像的中心应该是图像宽度的一半加上文本开头的缓冲区。你可以通过说imageContainer.center = CGPointMake(textContainer.frame.minX - imageContainer.frame.size.width * 0.5 - buffer,container.frame.size.height / 2)
来做到这一点。您的代码应该类似于:
let container = UIView(frame: CGRectMake(0,0,200,40))
let buffer:CGFloat = 8.0
let maxWidth:CGFloat = 120.0
let imageContainer = UIImageView(frame: CGRectMake(0, 0, 30, 30))
imageContainer.image = UIImage(named: "profile.jpg")
let textContainer = UILabel(frame: CGRectMake(0,0, 180, 20))
textContainer.text = "Group xY"
textContainer.adjustsFontSizeToFitWidth = true
textContainer.minimumScaleFactor = 0.95
textContainer.sizeToFit()
textContainer.frame.size.width = min(maxWidth, textContainer.frame.size.width)
textContainer.center = CGPointMake(container.frame.size.width / 2,
container.frame.size.height / 2)
imageContainer.center = CGPointMake(textContainer.frame.minX - imageContainer.frame.size.width * 0.5 - buffer,
container.frame.size.height / 2)
container.addSubview(imageContainer)
container.addSubview(textContainer)