Set frame (CGRect) per devices by count of characters - Swift 3

不羁岁月 提交于 2019-12-12 05:28:40

问题


I'm creating label and characters, I want set frame (X, Y and width) of UILabel by characters and Y-axis is constant of all devices, so how can I set center of X-axis and controlling by count of characters, and width (50) gets smaller and bigger per device ??

This my code :

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)

     }
}

In this picture is my label its position is center of X-axis of iPhone 7 plus simulator and numbers of label it's per count of characters, so I want like this position (X, Y and width) in all devices and width gets smaller and biggest and if count of characters for example is 9 it's must be on center of X-axis and width must be gets smaller little and spaces right and left of device.

How can I do it ?!

Thank you :)


回答1:


This is the 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)

        }

    }

}


来源:https://stackoverflow.com/questions/45209791/set-frame-cgrect-per-devices-by-count-of-characters-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!