代码之家  ›  专栏  ›  技术社区  ›  XtremeDevX

UILabel未显示在视图中

  •  -1
  • XtremeDevX  · 技术社区  · 5 年前

    enter image description here

    我刚刚开始学习如何在不使用故事板的情况下编程,所以请把我当作初学者。。。即使我的图像出现在屏幕上,标签也没有……我有点困惑为什么会这样,我很感激你的帮助。再说一次,我是个初学者,不介意这是一个愚蠢的错误!!!

    import UIKit
    
    class LocationRequestController : UIViewController
    {
        let imageView: UIImageView =
        {
            let iconImageView = UIImageView()
            iconImageView.contentMode = .scaleAspectFit
            iconImageView.image = UIImage(named: "blue-pin")
            return iconImageView
        }()
    
        let allowLocationLabel : UILabel =
        {
            let label = UILabel()
            let attributedText = NSMutableAttributedString(string: "Allow Location\n", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 24)])
            attributedText.append(NSAttributedString(string: "Please enable location services For The Map To Work!", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]))
    
            label.numberOfLines = 0
            label.textAlignment = .center
            label.attributedText = attributedText
    
            return label
        }()
        override func viewDidLoad()
        {
            super.viewDidLoad()
            configureViewAppearance()
        }
    
        func configureViewAppearance()
        {
            view.backgroundColor = .white
    
            view.addSubview(imageView)
            imageView.anchor(top: view.topAnchor, left: nil, bottom: nil, right: nil, paddingTop: 140, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 200, height: 200)
            imageView.centerX(inView: view)
    
            view.addSubview(allowLocationLabel)
            allowLocationLabel.anchor(top: imageView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 32, paddingLeft: 32, paddingBottom: 0, paddingRight: 32, width: 0, height: 0)
            allowLocationLabel.centerX(inView: view)
        }
    }
    

    再次感谢!

    2 回复  |  直到 5 年前
        1
  •  0
  •   Jawad Ali    5 年前

    你只需要添加一行 label.translatesAutoresizingMaskIntoConstraints

    let allowLocationLabel : UILabel =
        {
            let label = UILabel()
            let attributedText = NSMutableAttributedString(string: "Allow Location\n", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 24)])
            attributedText.append(NSAttributedString(string: "Please enable location services For The Map To Work!", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]))
    
            label.numberOfLines = 0
            label.textAlignment = .center
            label.attributedText = attributedText
            label.translatesAutoresizingMaskIntoConstraints = false
            return label
        }()
    
        2
  •  -1
  •   XtremeDevX    5 年前

    这就是问题所在:

    文本颜色自动设置为.白色,这就是它似乎没有显示的原因!谢谢大家的帮助!