我想从外部将UILabel添加到我的库的collection view单元格中

时间:2019-04-23 03:59:09

标签: swift frameworks

对于我的github库中的PageCell0文件, 我想在项目中使用扩展名来引入库,并使用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
    }
}

```

2 个答案:

答案 0 :(得分:0)

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

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

编辑:这是一个基本示例,其中删除了一些填充代码,并对代码进行了一些改进。我将在您的init中设置单元格值。您还需要init编码器(在移动设备上,因此没有添加)。

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

            ])

    }
}

答案 1 :(得分:0)

您不应将subView直接添加到Cell。改为这样做:

cell.contentView.addSubview(subView1)