Organize and adjust the UILabel position per devices - Swift 3

旧街凉风 提交于 2019-12-13 07:26:56

问题


I have SQLite database file and UILabel, and I set text for label from database on the number of characters after convert String to Characters, and I added extension its name (length), its job counts the number of characters.

My problem in this picture is : The UILabels are not organized in sizes and positions in per devices I want them to have their positions in the center of X-Axis

Questions:

1) How to set the label into center and set spaces right and left of screen for labels (per device) ??

2) How to set width for labels if device is iPhone 7/6S/6 plus width = 50, if device is iPhone 7/6S/6 width = 45 and if device is iPhone SE/5S/5C/5 width = 38 ??

3) Finally, how does the label become smaller by 10 if the number of characters is more than 8 ?

This my code :

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) * 60%
        let width: CGFloat = view.frame.size.width - 40 // frame width
        var targetWidth: CGFloat = (width - (lengthOfChar - 1) * 5) / lengthOfChar
        let targetHeigt : CGFloat = 5

        if lengthOfChar >= 8 {
            targetWidth = 40
        } else {
            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: targetHeigt))
            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)

        }

    }

}

回答1:


In order to position your labels you need a few things things:

  1. Label container to keep everything centered and with margins from the screen sides
  2. Constraints between your labels depending on the device sizes etc..
  3. If you need to break lines - you need to handle it manually as well

To identify device kinds and have different logics, you can check this posts: iOS: How to determine the current iPhone/device model in Swift?

In order to fill your view with labels, here is a sample code to achieve this:

self.view.backgroundColor = UIColor.black

let labelContainerView : UIView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
labelContainerView.translatesAutoresizingMaskIntoConstraints = false

let containerLeftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: self.view, attribute: .left, relatedBy: .greaterThanOrEqual, toItem: labelContainerView, attribute: .left, multiplier: 1, constant: 8)
let containerRightConstraint : NSLayoutConstraint = NSLayoutConstraint(item: self.view, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: labelContainerView, attribute: .right, multiplier: 1, constant: 8)
let containerCenterX : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let containerCenterY : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)

self.view.addSubview(labelContainerView)
self.view.addConstraints([ containerLeftConstraint, containerRightConstraint, containerCenterX, containerCenterY ])

// Add some labels
let totalLabels : Int = 10

var lastAddedLabel : UILabel? = nil

for labelAt : Int in 1 ... totalLabels
{
    var addedConstraint : [NSLayoutConstraint] = [NSLayoutConstraint]()

    let label : UILabel = UILabel(frame: CGRect.zero)
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "_"
    label.textColor = UIColor.white
    label.textAlignment = .center
    label.adjustsFontSizeToFitWidth = true

    if (lastAddedLabel != nil)
    {
        // Add left constraint to previous label
        let leftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: label, attribute: .left, relatedBy: .equal, toItem: lastAddedLabel!, attribute: .right, multiplier: 1, constant: 8)
        let equalWidth : NSLayoutConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: lastAddedLabel!, attribute: .width, multiplier: 1, constant: 0)

        addedConstraint.append(contentsOf: [ leftConstraint, equalWidth ])
    }
    else
    {
        // Add left constraint to super view
        let leftConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .left, relatedBy: .equal, toItem: label, attribute: .left, multiplier: 1, constant: 0)

        addedConstraint.append(leftConstraint)
    }

    // Add top bottom constraint
    let topConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .top, relatedBy: .equal, toItem: label, attribute: .top, multiplier: 1, constant: 0)
    let bottomConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .bottom, relatedBy: .equal, toItem: label, attribute: .bottom, multiplier: 1, constant: 0)

    addedConstraint.append(contentsOf: [ topConstraint, bottomConstraint ])

    // Add right constraint if this is the last label
    if (labelAt == totalLabels)
    {
        let rightConstraint : NSLayoutConstraint = NSLayoutConstraint(item: labelContainerView, attribute: .right, relatedBy: .equal, toItem: label, attribute: .right, multiplier: 1, constant: 0)

        addedConstraint.append(rightConstraint)
    }

    labelContainerView.addSubview(label)
    labelContainerView.addConstraints(addedConstraint)

    lastAddedLabel = label
}

self.view.layoutIfNeeded()

This gives out the output:

Changes you might need to make:

  1. Change the "totalLabels" number depending on your requirement
  2. Maybe adding another width constraint to the first generated label in order to define a specific with for all labels - the rest of the labels keep the same width as the first
  3. Adjust the containing view margins from both sides for different devices
  4. Handle new lines manually by pre-calculating the width the labels might use.

Good luck




回答2:


I solved my problem and this answer :

func createTarget(id: Int) {

    listdata = dbHelpr.getDatabase(rowId: id)
    var targetHeigt = CGFloat()
    let viewWidth = self.view.frame.size.width
    if viewWidth == 320 {
        targetHeigt = 2.5
    } else {
        targetHeigt = 5
    }

    for data in listdata {
        let yAxis : CGFloat = (self.view.frame.height) * 60%
        let i = data.ans.length
        // char count
        let width: Int = Int(view.frame.size.width) - 40

        // frame width
        var targetWidth: Int = (width - (i - 1) * 5) / i

        if targetWidth > 50 {
            targetWidth = 50
        }
        let totalWidth: Int = (targetWidth * i) + ((i - 1) * 5)

        for x in 0..<i {
            let currentWidth: Int = (width / 2) - (totalWidth / 2) + (x * targetWidth) + (x * 5) + 20

            let targetLabel = UILabel(frame: CGRect(x: CGFloat(currentWidth), y: yAxis, width: CGFloat(targetWidth), height: targetHeigt))
            targetLabel.backgroundColor = .white
            targetLabel.layer.masksToBounds = true
            targetLabel.layer.cornerRadius = 5
            targetLabel.textAlignment = .center
            targetLabel.textColor = .white

            for i in listdata {
                let tar = data.ans.characters.map{String($0)}
                targetLabel.text = String(describing: tar)
            }
            self.view.addSubview(targetLabel)
        }
    }
}


来源:https://stackoverflow.com/questions/45544072/organize-and-adjust-the-uilabel-position-per-devices-swift-3

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