swift 中的自定义 UIView
Custom UIView in swift
我正在创建一个自定义 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
创建此视图的实例时。
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
的子视图,而不是 AnswersCustomView
父视图,因此您应该将标签的框架设置为它的父视图边界。
另一种是自动布局:您没有使用它。我不知道你是如何创建 AnswerView 的,如果它的初始帧为零,你的标签将保持为零,你应该添加它并设置约束或至少自动调整掩码。
另一个可能是如果你在 xib 中创建视图,在这种情况下 iniWithCoder
被调用并且在这里你没有放置任何标签。
为了简化视图调试,Apple 添加了一个新工具,可以在 3d 中显示视图层次结构 https://www.raywenderlich.com/98356/view-debugging-in-xcode-6
我正在创建一个自定义 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
创建此视图的实例时。
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
的子视图,而不是 AnswersCustomView
父视图,因此您应该将标签的框架设置为它的父视图边界。
另一种是自动布局:您没有使用它。我不知道你是如何创建 AnswerView 的,如果它的初始帧为零,你的标签将保持为零,你应该添加它并设置约束或至少自动调整掩码。
另一个可能是如果你在 xib 中创建视图,在这种情况下 iniWithCoder
被调用并且在这里你没有放置任何标签。
为了简化视图调试,Apple 添加了一个新工具,可以在 3d 中显示视图层次结构 https://www.raywenderlich.com/98356/view-debugging-in-xcode-6