按字符数设置每个设备的帧(CGRect) - Swift 3

时间:2017-07-20 08:48:07

标签: swift uilabel frame cgrect

我正在创建标签和字符,我想要按字符设置UILabel的框架(X,Y和宽度),Y轴是所有设备的常量,那么如何设置X轴的中心并按计数控制字符和宽度(50)每个设备变得越来越小?

这是我的代码:

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轴的中心,宽度必须小一些,并且设备的左右空间。

我该怎么做?!

谢谢:)

1 个答案:

答案 0 :(得分: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)

        }

    }

}