Swift & UILabel:如何以编程方式在 Swift 中添加填充和边距?

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

我使用 UILabel 以编程方式创建了一个灰色背景的文本。 现在我想将 padding 添加到此 paragraph/text。另外,如果你能告诉我如何将 margin 添加到我的 UILabel 中,那就太好了。

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
    }
}

请注意,我为 UIColor 创建了一个扩展,以便我可以用这种方式输入十六进制颜色 - UIColor().colorFromHex(hex: "#2C333C", opacity: 0.4) .

期待您的来信。谢谢。

您可以将此 UILabel 插入容器(任何 UIView)并在其中设置其位置。

但最简单的技巧是使用 UIButton 而不是 UILabel。您可以为填充配置 UIEdgeInsets。

这样 UIButton 就不会充当按钮,只需设置 button.isUserInteractionEnabled = false。

默认情况下,按钮中的文本位于中心,但其位置很容易通过 contentHorizo​​ntalAlignment 和 contentVerticalAlignment 更改

作为奖励,您可以在文本附近添加图标。 :)

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 :)

当然,如果愿意,您可以使用故事板来完成。

1.添加此 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。将此代码添加到您的 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)   
}

下面link的答案是我根据故事板写了同样的内容

我用textfield。在文本字段中设置填充和文本。并且不允许编辑。

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"
}