布局子视图无法正常工作

时间:2014-06-27 14:53:05

标签: uiview swift

我设计的自定义视图遇到了麻烦。 它本质上是一个显示12个标签的表,其中左上标签和左下标签必须是其他视图的宽度* 5。我已经添加了视图并调整了布局子视图中的框架,但标签没有出现在视图中(已经使用Xcode的新视图调试器进行了检查

 override func layoutSubviews() {
    super.layoutSubviews()

    let width = self.frame.size.width
    let height = self.frame.size.height

    let normalWidth = width/10
    let normalHeight = height/2


    var currentOrigin = CGPoint(x: 0, y: 0)

    let nameSize = CGSize(width: normalWidth * 5 - 3, height: normalHeight)

    labels[0][0].frame = CGRect(origin: currentOrigin, size: nameSize)

    currentOrigin.x += normalWidth

    for j in labels[0]{
        j.frame = CGRect(origin: currentOrigin, size: CGSize(width: normalWidth - 3, height: normalHeight))
        currentOrigin.x += normalWidth
    }

    currentOrigin.y = normalHeight
    currentOrigin.x = 0
    labels[1][0].frame = CGRect(origin: currentOrigin, size: nameSize)

    for j in labels[1]{
        j.frame = CGRect(origin: currentOrigin, size: CGSize(width: normalWidth - 3, height: normalHeight))
        currentOrigin.x += normalWidth
    }
}

这是我使用的构造函数。根据调试器,视图位于superview中,但它们不可见

 init(frame: CGRect) {
    labels = Array(count:2, repeatedValue:Array(count:6, repeatedValue: UILabel() ))
    super.init(frame: frame)

    for i in 0..labels.count{
        for j in 0..labels[i].count{
            labels[i][j] = UILabel()
            labels[i][j].font = currentFont
            labels[i][j].adjustsFontSizeToFitWidth = true
            labels[i][j].textAlignment = NSTextAlignment.Center
            labels[i][j].text = "HOLA MUNDO"
            addSubview(labels[i][j])
        }
    }

    for i in 0..labels.count{
        if let k = delegate?{
            labels[i][0].text = k.name(i+1)
        }
    }


    for i in 0..labels.count{
        for j in 1..labels[i].count{
            labels[i][j].text = "0"
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果有人遇到类似的麻烦,我终于找到了解决方案

 labels = Array(count:2, repeatedValue:Array(count:6, repeatedValue: UILabel() ))

此行生成2个UILabel数组,但所有数组项都指向UILabel的同一个实例。也:

  labels[0] === labels[1] //They will point to the same instance

另一个错误是在

中迭代
 for i in 0..labels.count{
    if let k = delegate?{
        labels[i][0].text = k.name(i+1)
    }
}

正确的做法是从1迭代到labels.count,因为第一个标签必须具有不同的大小。

实现数组的正确形式如下:

  for i in 0..2{
        labels.append([UILabel]())
        for j in 0..6{
            labels[i].append(UILabel())
            labels[i][j].font = currentFont
            labels[i][j].adjustsFontSizeToFitWidth = true
            labels[i][j].textAlignment = NSTextAlignment.Center
            labels[i][j].text = "HOLA MUNDO"
                addSubview(labels[i][j])

        }

希望它可以帮助您避免此错误。真的很难找到。