Set frame (CGRect) to devices by number of characters - Swift 3

I am creating a shortcut and symbols, I want to set the frame (X, Y and width) of the UILabel by symbols and the Y axis is constant for all devices, since I can set the center of the X axis and control the character count, and the width (50) gets smaller and more per device?

This code of mine:

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

In this picture, my label its position is the center of the X-axis of the iPhone 7 plus the simulator and the number of labels per number of characters, so I want how this position (X, Y and width) on all devices and the width gets smaller and larger, and if the number of characters for example equal to 9, it should be in the center of the x-axis, and the width should be smaller, and space should be left and right of the device.

How can i do this?!

Thank:)

0


source to share


1 answer


This solution:



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)

        }

    }

}

      

0


source







All Articles