添加NSLayoutConstraint后,视图消失

时间:2016-04-29 01:46:09

标签: swift nslayoutconstraint

当我向视图添加NSLayoutConstraint时,会导致视图消失。

我使用以下代码:

Sub ActualizarNoticias()
     Dim aw As Workbook
     Dim y As Workbook

Set aw = Application.ActiveWorkbook
Set y = Application.Workbooks.Open("G:\Estudios\Biblioteca\Mercado Accionario Chileno\BBDD Oficial.xlsm")


For i = 1 To aw.Sheets.Count
For j = 1 To y.Sheets.Count

If aw.Worksheets(i).Name = y.Worksheets(j).Name Then

y.Worksheets(j).Range("A3").Copy
aw.Worksheets(i).Range("A100").PasteSpecial
End If

Next j
Next i

y.close
' ActualizarNoticias Macro
'
'
End Sub

当我调试视图层次结构时,我看到视图存在,即使它不可见。有关详细信息,请参阅下面的屏幕截图 - 只有约束是可见的,而不是视图: enter image description here

1 个答案:

答案 0 :(得分:1)

这里有很多事情需要讨论。

  1. 使用以下内容时

    test.translatesAutoresizingMaskIntoConstraints = false
    

    然后它将完全依赖约束来定位和调整视图大小。所以你需要设置视图的高度和宽度约束。

    let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100)
    
    let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100)
    
  2. 最后这将是您正在寻找的代码

                let test:UIView = UIView(frame: CGRectMake(0, 0, 100, 100))
        test.backgroundColor = UIColor.blackColor()
        self.view.addSubview(test)
        test.translatesAutoresizingMaskIntoConstraints = false
        let topCKCtr = NSLayoutConstraint(item: test, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 0.5, constant: 0)
        topCKCtr.active = true
        let topCKCtr1 = NSLayoutConstraint(item: test, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 0.5, constant: 0)
        topCKCtr1.active = true
    
        let topCKCtr2 = NSLayoutConstraint(item: test, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 100)
        topCKCtr2.active = true
    
        let topCKCtr3 = NSLayoutConstraint(item: test, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 100)
        topCKCtr3.active = true