首页 > 解决方案 > 我想从外部添加一个 UILabel 到我图书馆的收藏视图单元格

问题描述

对于我在github的库中的文件PageCell0,我想在项目中使用exetension来引入库并使用addSubView添加UILabel(newLabel)。

我在介绍库的地方写了如下,但是因为UILabel即使构建了模拟器也不会显示,所以很困扰。

我正在寻找解决方案,但我不知道。

//Project file that introduced the library

import UIKit
import SlidingCellWithDrag0Framework

class ViewController: MainViewController {
    var cell1: PageCell1?

    var newLabel: UILabel = {
        let nL = UILabel()
        nL.textColor = UIColor.yellow
        nL.text = "newLabel"
     nL.translatesAutoresizingMaskIntoConstraints = false
        return nL
    }()

    override func viewDidLoad() {
        super.viewDidLoad() 

        cell1?.addSubview(newLabel)

     newLabel.anchor(top: cell1?.topAnchor,
             leading: cell1?.leadingAnchor,
             bottom: nil,
             trailing: cell1?.trailingAnchor,
             padding: .init(top: 10, left: 20, bottom: 10, right: 30),
             size: .init(width: 300,
             height: 150))

    }
}

:编辑代码



// AppDelegate

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


  window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()        
        let home = UINavigationController(rootViewController : ViewController())
        window?.rootViewController = home
    return true
    }
}

```

标签: swiftframeworks

解决方案


不确定您的 newLabel.anchor 函数是否是扩展。但看起来您正在添加标签而不是使用自动布局。因此,您需要添加newLabel.translatesAutoresizingMaskIntoConstraints = false因此您的标签不使用自动布局。这可以在您将标签添加为子视图之前或之后添加。

https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco

编辑:这是一个基本示例,删除了一些填充代码,代码略有改进。我会在你的初始化中设置单元格值。您还需要初始化编码器(在移动设备上,所以没有添加它)。

import UIKit
import SlidingCellWithDrag0Framework

class ViewController: MainViewController {
    var cell1: PageCell1?

    var newLabel: UILabel = {
        let nL = UILabel()
        nL.textColor = UIColor.yellow
        nL.text = "newLabel"
        nL.translatesAutoresizingMaskIntoConstraints = false

        return nL
    }()

    init(cell1: PageCell1) {
        self.cell1 = cell1
    }

    // You'll need init coder here too

    override func viewDidLoad() {
        super.viewDidLoad() 

        cell1.addSubview(newLabel)
        NSLayoutConstraint.activate([
            newLabel.leadingAnchor.constraint.equalTo(cell1.leadingAnchor),
            newLabel.trailingAnchor.constraint.equalTo(cell1.trailingAnchor),
            newLabel.topAnchor.constraint.equalTo(cell1.topAnchor) // This is just a placeholder

            ])

    }
}


推荐阅读