简体   繁体   中英

Swift & UILabel : How to add padding and margin in Swift programmatically?

I have created a text programmatically with a grey background using UILabel. Now I would like to add padding to this paragraph/text. Also, it would be great if you could show me how to add margin to my UILabel as well.

import UIKit

final class SignUpViewController: UIViewController {
    
    public let identifier = "Sign Up"
    
    private let logoImage : UIImageView = {
        let imageView = UIImageView()
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFit
        imageView.image = UIImage(named: "MyLogoWithTitle")
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private let instructionText : UILabel = {
        let label = UILabel()
        label.text = "Please read terms and conditions below carefully before proceeding with the registration."
        label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
        label.numberOfLines = 0
        label.tintColor = .white
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.addSubview(logoImage)
        view.addSubview(instructionText)
        view.backgroundColor = UIColor().colorFromHex(hex: "#141920", opacity: 1.0)
    
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        logoImage.frame = CGRect(x: 0,
                                 y: 0,
                                 width: 140,
                                 height: 60)
        logoImage.center = CGPoint(x: view.center.x, y: view.height/5)
        
        instructionText.frame = CGRect(
            x: 5,
            y: 5 + logoImage.bottom,
            width: view.width - 20,
            height: 50)
            .integral
        instructionText.layer.cornerRadius = 10
    }
}

Notice that I created an extension to UIColor so that I can input hex color in this way - UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4) .

I am looking forward to hearing from you. Thank you.

You can insert this UILabel into the container (any UIView) and set its position inside.

But the simplest trick is to use UIButton instead of UILabel. You can configure UIEdgeInsets for padding.

So that UIButton does not act as a button simply set button.isUserInteractionEnabled = false.

By default, text in the button are placed in the center, but its position is easy to change with contentHorizontalAlignment and contentVerticalAlignment

And as a bonus, you can add icons right near to the text. :)

UPD.

Could you give me a simple example? I tried that way but I didn't get the result I expected. – Punreach Rany

let buttonUsedAsLabel = UIButton()
// Your question was about padding
// It's it!
buttonUsedAsLabel.titleEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)
// Make it not user interactable as UILabel is
buttonUsedAsLabel.isUserInteractionEnabled = false
// set any other properties
buttonUsedAsLabel.setTitleColor(.white, for: .normal)
buttonUsedAsLabel.contentVerticalAlignment = .top
buttonUsedAsLabel.contentHorizontalAlignment = .left
// Set title propeties AFTER it was created with text because it's nullable
// You can use attributed title also
// Never use any (button.titleLabel) before its creation
// for example: (button.titleLabel?.text = "zzz") do nothing here
buttonUsedAsLabel.setTitle("This is the text", for: .normal)
buttonUsedAsLabel.titleLabel?.font = .systemFont(ofSize: 20, weight: .medium)
buttonUsedAsLabel.titleLabel?.numberOfLines = 0
buttonUsedAsLabel.titleLabel?.lineBreakMode = .byWordWrapping
// and so on
//    ...
// This is the triсk :)

Of course, you can do it with a storyboard if prefer.

1. Add this class

PaddingLabel.swift

import UIKit

class PaddingLabel: UILabel {

    var edgeInset: UIEdgeInsets = .zero

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets.init(top: edgeInset.top, left: edgeInset.left, bottom: edgeInset.bottom, right: edgeInset.right)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + edgeInset.left + edgeInset.right, height: size.height + edgeInset.top + edgeInset.bottom)
    }
}

2. Add this code to your ViewController

let label = PaddingLabel()

override func viewDidLoad() {
    super.viewDidLoad()
    
    label.backgroundColor = UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4)
    
    //Setting the padding label
    label.edgeInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)   
}

The answer to the link below is that I wrote the same content based on the storyboard.

I use textfield . Set padding and text in textfield. And do not allow editing.

extension UITextField {
    
    func addLeftPadding() {
        
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: self.frame.height))
        self.leftView = paddingView
        self.leftViewMode = ViewMode.always
    }
}
//ViewController

@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
  super.viewDidLoad()
  myTextField.addLeftPadding()
  myTextField.isUserInteractionEnabled = false
  myTextField.text = "your label text"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM