2017-07-20 86 views
0

我正在創建標籤和字符,我想要通過字符設置UILabel的框架(X,Y和寬度),並且Y軸是所有設備的常量,那麼如何設置X軸的中心和字符的數量來控制,寬度(50)每個設備越來越小?通過字符數設置每個設備的框架(CGRect) - Swift 3

這是我的代碼:

func createTarget(id: Int) { 

    listdata = dbHelpr.getDatabase(rowId: id) 

    for data in listdata { 

     let lengthOfChar : CGFloat = data.ans.length 
     let targetSize : CGFloat = self.view.frame.width/2 
     var xAxis : CGFloat = self.view.frame.width/2 + 55 
     let yAxis : CGFloat = self.view.frame.height/2 + 70 
     let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: 50, height: 5)) 
     xAxis -= 50 + (lengthOfChar) 

    } 
} 

enter image description here

在這張照片是我的標籤,它的位置是iPhone 7的X軸加模擬器和標籤是每個字符數是數的中心,所以我想在所有設備中這個位置(X,Y和寬度)和寬度變得更小和最大,如果字符數例如是9,它必須位於X軸的中心,寬度必須變小一點,設備左側。

我該怎麼辦?

謝謝:)

+2

使用'Autolayouts'。將標籤放在堆棧視圖中,並將堆棧視圖設置爲「水平居中」和「垂直居中」 – pkc456

回答

0

這是解決方案:

func createTarget(id: Int) { 

    listdata = dbHelpr.getDatabase(rowId: id) 

    for data in listdata { 

     let lengthOfChar : CGFloat = data.ans.length 
     let yAxis : CGFloat = self.view.frame.height/2 + 70 

     let width: CGFloat = view.frame.size.width - 40 // frame width 
     var targetWidth: CGFloat = (width - (lengthOfChar - 1) * 5)/lengthOfChar 

     if targetWidth > 50 { 
      targetWidth = 50 
     } 

     let totalWidth: CGFloat = (targetWidth * lengthOfChar) + ((lengthOfChar - 5) * 5) 

     for (indexTar, tar) in data.ans.characters.enumerated() { 

      let x : CGFloat = (width/2) - (totalWidth/2) 
      let xx : CGFloat = (CGFloat(indexTar) * targetWidth) + (CGFloat(indexTar) * 5) + 20 
      var xAxis : CGFloat = (x + xx) 
      xAxis = width - xAxis 

      let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: targetWidth, height: 5)) 

      targetLabel.backgroundColor = .white 
      targetLabel.layer.masksToBounds = true 
      targetLabel.layer.cornerRadius = 5 
      targetLabel.text = String(describing: tar) 
      targetLabel.textAlignment = .center 
      targetLabel.textColor = .white 
      self.view.addSubview(targetLabel) 

     } 

    } 

}