swift - 我想从外部添加一个 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
}
}
```
解决方案
不确定您的 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
])
}
}
推荐阅读
- django-rest-framework - Django rest框架:将成功或失败的请求记录到文本文件
- utf-8 - 所有权问题(不可变和可变借用的情况)
- regex - 如何使用 Go regexp 查找特定模式的所有匹配项并捕获组
- sql - 仅从带有条件的 SQL 表中的一列中选择值
- html - @page 规则在浏览器中不起作用
- java - 将证书和私钥加载到 Java KeyStore 中
- r - R中的数据(行)操作
- django - from_db_value() 接受 4 个位置参数,但 Django 给出了 5 个
- xamarin - 在 Xamarin 中设置 .SFUI-* 字体似乎可以正确使用字体扩展名进行转换,但仍然出现警告错误
- tensorflow - 在 TF2 的损失函数中使用中间层的输出