问题
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