【发布时间】:2015-08-15 19:23:25
【问题描述】:
到目前为止,我创建了自己的自定义视图,它是 UIView 类的子类:
class MyConnections: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 1)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
let circle = CGRectMake(5, 60, 80, 80)
CGContextAddEllipseInRect(context, circle)
CGContextStrokePath(context)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillEllipseInRect(context, circle)
}
}
这是我的视图控制器,我将上面的视图添加为子视图:
let profile = MyConnections()
override func viewDidLoad() {
super.viewDidLoad()
profile.backgroundColor = UIColor.clearColor()
view.addSubview(profile)
self.profile.setTranslatesAutoresizingMaskIntoConstraints(false)
//constraints for the location button
let horizontalConstraint = NSLayoutConstraint(item: self.profile, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 10)
let verticalConstraint = NSLayoutConstraint(item: self.profile
, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20)
let widthConstraint = NSLayoutConstraint(item: self.profile, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 150)
let heightConstraint = NSLayoutConstraint(item: self.profile, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 150)
self.view.addConstraints([verticalConstraint, horizontalConstraint, widthConstraint, heightConstraint])
// Do any additional setup after loading the view.
}
上面的所有代码都给了我一个圆圈。现在我想在图像中看到的不同位置多次重复同一个圆圈。我可以创建 uiview 的多个实例,将它们添加为子视图,但每次我都必须为它定义我不想做的新约束。
谁能帮助我并给我一个有效的答案?
【问题讨论】:
-
UICollectionView可能更适合这样的事情。 -
UICollectionView怎么样? -
@rmaddy 我想在不使用情节提要的情况下创建一个集合视图。我的整个项目使用 .xib 文件。我找不到任何显示在没有情节提要的情况下创建集合视图的教程。你能在这里分享一些链接吗?
标签: ios swift uiview uiviewcontroller