我正在创建一个自定义 UIView
,它应该包含一个 UIImageView
和一个 UILabel
这是它的类(class)。
import UIKit
class AnswersCustomView: UIView {
var myImageView = UIImageView()
var myLabel = UILabel()
override init (frame : CGRect) {
super.init(frame : frame)
backgroundColor = UIColor.blueColor()
addLabel()
bringSubviewToFront(myLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addLabel(){
let myViewFrame = self.frame
myLabel.frame = myViewFrame
myLabel.backgroundColor = UIColor.redColor()
myLabel.center=self.center
addSubview(myLabel)
}
}
每当我从 UIViewController
创建此 View 的实例时。
添加了 UIView
但似乎没有添加 UILabel
。
有什么理由吗?
最佳答案
正如评论中已经指出的,一个问题可能是标签的框架不正确。
正如 Apple 文档中所述,该框架是:
This rectangle defines the size and position of the view in its superview’s coordinate system. You use this rectangle during layout operations to size and position the view. Setting this property changes the point specified by the center property and the size in the bounds rectangle accordingly. The coordinates of the frame rectangle are always specified in points.
您创建的标签是 AnswersCustomView
实例的 subview ,而不是 AnswersCustomView
super View ,因此您应该将标签的框架设置为它的 super View 边界。
另一个是自动布局:您没有使用它。我不知道你是如何创建 AnswerView 的,如果它的初始帧为零,你的标签将保持为零,你应该添加它并设置约束或至少自动调整掩码。
另一种可能是如果您在 xib 中创建 View ,在这种情况下 iniWithCoder
被调用并且您没有放置任何标签。
为了简化 View 调试,Apple 添加了一个新工具,可以以 3d 形式显示 View 层次结构 https://www.raywenderlich.com/98356/view-debugging-in-xcode-6
关于ios - 快速自定义 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36234117/