【发布时间】:2016-01-10 16:40:53
【问题描述】:
我有一个静态图像,上面有一个区域,用于显示一些多行文本。就像电子游戏中角色的讲话泡泡。我抓住了一张看起来像这样的库存图片:
我有一个 UIImageView 设置为在主视图的子视图内适合宽高比(参见question)。我还在子视图中设置了一个 UILabel,它将保存多行文本。我希望能够在屏幕上移动子视图并使其具有任何大小,并且 UIImageView 仍然保持相同的方面,并且 UILabel 适合图像的气泡。
我创建了一个sample project,它已经设置好了。
我打算将 UILabel 的边界保持在对话气泡区域内的方法是设置与 UIImageView 的中心 x 和 y 成比例的约束。对于我的图像,左边的乘数是 0.65,右边是 1.8,顶部是 0.19,底部是 0.63。
我编写了几个从 UIView 扩展的函数来确认这一点:
/**
Draws a vertical line proportional to the center x of the view.
A `proportional` value of 0 is the left edge, while 2 is the right edge.
:param: proportion The value from the left edge (0.0) to the right edge (2.0)
:param: inColor The color to draw the line in (red by default)
*/
func drawVertLineAtProportion(proportion: CGFloat, inColor: UIColor = UIColor.redColor()) {
let size = self.frame.size
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
let x = self.bounds.origin.x + proportion*self.frame.size.width/2
var vertPath = UIBezierPath()
vertPath.lineWidth = size.height/150.0
vertPath.moveToPoint(CGPointMake(x, 0))
vertPath.addLineToPoint(CGPointMake(x, self.frame.size.height))
inColor.setStroke()
vertPath.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.addSubview(UIImageView(image: image))
}
和drawHorizLineAtProportion 类似,但用于水平线。
我可以通过在viewDidAppear 中运行这 4 行来确认我的乘数值是正确的:
imageView.drawVertLineAtProportion(0.65)
imageView.drawVertLineAtProportion(1.8)
imageView.drawHorizLineAtProportion(0.19)
imageView.drawHorizLineAtProportion(0.63)
然后imageView看起来是这样的:
我可以将包含 imageView 的 subView 的大小更改为我想要的任何大小,并且 imageView 保持宽高比,并且这些红线交叉处的红色框始终正是我想要的。
那么,当我设置 UILabel 边缘的约束以遵循相同的公式时,为什么边缘不对齐?
似乎当imageView的宽度最大化时左右边缘是正确的但顶部和底部是错误的:
而如果高度达到最大值,则上下是正确的,但左右是错误的:
那么为什么 UILabel 边界不与红线对齐?
编辑指定我知道有一个运行时修复,但我想知道为什么故事板不起作用。
如果我在viewDidAppear 中添加这些行来修复 UILabel 的框架,它会起作用:
let upperLeft: CGPoint = CGPointMake(imageView.frame.origin.x + 0.65*imageView.frame.size.width/2, imageView.frame.origin.y + 0.19*imageView.frame.size.height/2)
let lowerRight: CGPoint = CGPointMake(imageView.frame.origin.x + 1.8*imageView.frame.size.width/2, imageView.frame.origin.y + 0.63*imageView.frame.size.height/2)
let size: CGSize = CGSizeMake(lowerRight.x - upperLeft.x, lowerRight.y - upperLeft.y)
speechLabel.frame = CGRectMake(upperLeft.x, upperLeft.y, size.width, size.height)
但我仍然想知道为什么我在故事板中设置的内容不起作用。
【问题讨论】:
标签: ios storyboard autolayout alignment