swift - 在 Swift 中创建一个带有背景的 UIView

标签 swift uiview

我纯粹通过代码在 Controller 上创建一个 UIView(我根本没有使用 Storyboard。

这是该简单 View 的代码:

let greenView: UIView = {
    let v = UIView(frame: CGRect.zero)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = UIColor.rgb(red: 183, green: 202, blue: 45)
    v.layer.borderWidth = 1
    return v
}()

当我在屏幕上设置 View 时:

    view.addSubview(greenView)
    greenView.anchor(top: joined.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 20, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: view.frame.width - 20, height: 200)

这个“ anchor ”功能只是帮助设置自动布局约束的扩展,它适用于所有其他组件,例如实际上继承自 UIView 的 UIButton。

问题: View 没有显示在屏幕上的任何位置……我是不是漏掉了什么?

对于我使用的 anchor 方法 LBTAComponents .

更具体地说 this class 到目前为止,所有其他方法都运行良好。

最佳答案

你说你正在使用 LBTAComponents ,但您的方法签名不匹配。他们很接近,但看起来他们正在使用一些旧版本(查看历史,我没有看到与您在上面使用的方法签名相匹配的旧版本)或者您有自己的扩展包装这个 API .例如下面的代码:

greenView.anchor(top: joined.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 20, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: view.frame.width - 20, height: 200)

应该是:

greenView.anchor(joined.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 20, leftConstant: 20, bottomConstant: 0, rightConstant: 0, widthConstant: view.bounds.width - 20, heightConstant: 200)

当我更正方法签名并将其与最新版本的 LBTAComponents 一起使用时,代码工作正常。因此,问题必须在于这些扩展的版本(或您用来包装该库以生成上述 API 的任何层)。

关于swift - 在 Swift 中创建一个带有背景的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44829546/

相关文章:

ios - 从登录 View Controller 过渡到主页

ios - 将解析数据与 coredata 同步,如何确定要删除哪些对象?

ios - 为什么 contentView 在 scrollView 中有一个 y 偏移量

ios - 如何为以编程方式快速创建的 View 定义类和模块

ios - UILabel下的UIVIew动画

Swift NSFetchedResultsController 嵌套对象的最佳实践

ios:UIPageControl 的垂直位置不明确

ios - AFNetworking 中适用于 iOS 应用程序崩溃的 AWS 分析

ios - facebooksdk 无法快速获取 accesstoken

iphone - 如何去除 iPhone 中的阴影