Ios 如何将不同位置的相同uiview倍数添加到UIViewController?

Ios 如何将不同位置的相同uiview倍数添加到UIViewController?,ios,swift,uiview,uiviewcontroller,Ios,Swift,Uiview,Uiviewcontroller,我正试图通过swift实现这一目标 到目前为止,我创建了自己的自定义视图,它是UIView类的一个子类: class MyConnections: UIView { override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // Only override drawRect

我正试图通过swift实现这一目标

到目前为止,我创建了自己的自定义视图,它是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的多个实例,并将它们添加为子视图,但每次我都必须为其定义新的约束,这是我不想做的


有谁能帮我,给我一个有效的答案吗

您应该知道UIView可以有一个superview/父视图。如果将其作为子视图添加到其他位置(使用addSubview方法),它将从第一个位置删除,并作为子视图添加到新位置。 在您的情况下,要添加更多的子视图,您必须创建更多的UIView对象,而不是使用单个全局UIView。
如果布局重复,UITableView/UICollectionView是更好的选择。

您应该知道UIView可以有一个超级视图/父视图。如果将其作为子视图添加到其他位置(使用addSubview方法),它将从第一个位置删除,并作为子视图添加到新位置。 在您的情况下,要添加更多的子视图,您必须创建更多的UIView对象,而不是使用单个全局UIView。
如果布局重复,UITableView/UICollectionView是一个更好的选择。

您的需求和UI符合UICollectionView的条件,我认为您应该使用
UICollectionView
,并且可以创建一个自定义的
UICollectionViewCell
,其中还包括圆形图像和徽章视图,它们添加了数据源和委托方法。这不仅有助于创建用户界面,还可以通过重用单元格提高应用程序的性能
这是一个关于
UICollectionView
您的需求和UI是否符合UICollectionView的很好的教程。我认为您应该使用
UICollectionView
,并且可以创建一个自定义的
UICollectionViewCell
,其中还包括圆形图像和徽章视图,它们还添加了数据源和委托方法。这不仅有助于创建用户界面,还可以通过重用单元格提高应用程序的性能
这是一个关于
UICollectionView

的很好的教程,这里有一个简化的视图,可以通过编程方式创建集合视图: 以编程方式使集合视图和布局与编写代码的任何其他视图一样,并将其添加为子视图,如下所示:

lazy var myCollectionView : UICollectionView = {
    let layout = YourFlowLayout()
    layout.scrollDirection = self.direction;
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0

    let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    cv.dataSource = self
    cv.delegate = self
    cv.isPagingEnabled = true
    cv.backgroundColor = UIColor.clear
    cv.showsHorizontalScrollIndicator = false
    cv.showsVerticalScrollIndicator = false
    cv.allowsMultipleSelection = false
    return cv
}()
您的流程布局可能类似于:

mport UIKit

class Yourflowlayout: UICollectionViewFlowLayout {

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    return super.layoutAttributesForElements(in: rect)?.map {
        attrs in
        let attrscp = attrs.copy() as! UICollectionViewLayoutAttributes
        self.applyLayoutAttributes(attributes: attrscp)
        return attrscp
    }

}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    if let attrs = super.layoutAttributesForItem(at: indexPath as IndexPath) {
        let attrscp = attrs.copy() as! UICollectionViewLayoutAttributes
        self.applyLayoutAttributes(attributes: attrscp)
        return attrscp
    }
    return nil
}


func applyLayoutAttributes(attributes : UICollectionViewLayoutAttributes) {
    if attributes.representedElementKind != nil {
        return
    }

    if let collectionView = self.collectionView {
        let stride = (self.scrollDirection == .horizontal) ? collectionView.frame.size.width : collectionView.frame.size.height
        let offset = CGFloat(attributes.indexPath.section) * stride
        var xCellOffset : CGFloat = CGFloat(attributes.indexPath.item) * self.itemSize.width
        var yCellOffset : CGFloat = CGFloat(attributes.indexPath.item) * self.itemSize.height
        if(self.scrollDirection == .horizontal) {
            xCellOffset += offset;
        } else {
            yCellOffset += offset
        }
        attributes.frame = CGRect(x: xCellOffset, y: yCellOffset, width: self.itemSize.width, height: self.itemSize.height)
    }
}
}

您可以将collectionView作为子视图添加到其他类中,请确保
myCollectionView.translatesAutoResizezingMaskintoConstraints=false
,这样就可以应用约束并实际看到集合视图,当然还可以添加约束或给它一个框架


希望这能帮助别人

下面是一个简化视图,可以通过编程方式创建集合视图: 以编程方式使集合视图和布局与编写代码的任何其他视图一样,并将其添加为子视图,如下所示:

lazy var myCollectionView : UICollectionView = {
    let layout = YourFlowLayout()
    layout.scrollDirection = self.direction;
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0

    let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    cv.dataSource = self
    cv.delegate = self
    cv.isPagingEnabled = true
    cv.backgroundColor = UIColor.clear
    cv.showsHorizontalScrollIndicator = false
    cv.showsVerticalScrollIndicator = false
    cv.allowsMultipleSelection = false
    return cv
}()
您的流程布局可能类似于:

mport UIKit

class Yourflowlayout: UICollectionViewFlowLayout {

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    return super.layoutAttributesForElements(in: rect)?.map {
        attrs in
        let attrscp = attrs.copy() as! UICollectionViewLayoutAttributes
        self.applyLayoutAttributes(attributes: attrscp)
        return attrscp
    }

}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    if let attrs = super.layoutAttributesForItem(at: indexPath as IndexPath) {
        let attrscp = attrs.copy() as! UICollectionViewLayoutAttributes
        self.applyLayoutAttributes(attributes: attrscp)
        return attrscp
    }
    return nil
}


func applyLayoutAttributes(attributes : UICollectionViewLayoutAttributes) {
    if attributes.representedElementKind != nil {
        return
    }

    if let collectionView = self.collectionView {
        let stride = (self.scrollDirection == .horizontal) ? collectionView.frame.size.width : collectionView.frame.size.height
        let offset = CGFloat(attributes.indexPath.section) * stride
        var xCellOffset : CGFloat = CGFloat(attributes.indexPath.item) * self.itemSize.width
        var yCellOffset : CGFloat = CGFloat(attributes.indexPath.item) * self.itemSize.height
        if(self.scrollDirection == .horizontal) {
            xCellOffset += offset;
        } else {
            yCellOffset += offset
        }
        attributes.frame = CGRect(x: xCellOffset, y: yCellOffset, width: self.itemSize.width, height: self.itemSize.height)
    }
}
}

您可以将collectionView作为子视图添加到其他类中,请确保
myCollectionView.translatesAutoResizezingMaskintoConstraints=false
,这样就可以应用约束并实际看到集合视图,当然还可以添加约束或给它一个框架


希望这能帮助别人

UICollectionView
可能更适合这样做。使用
UICollectionView
怎么样?@rmaddy我想创建一个集合视图而不使用故事板。我的整个项目使用.xib文件。我找不到任何显示在没有故事板的情况下创建集合视图的教程。你能在这里共享一些链接吗?
UICollectionView
可能更适合这样做。一个
UICollectionView
怎么样?@rmaddy我想创建一个集合视图而不使用故事板。我的整个项目使用.xib文件。我找不到任何显示在没有故事板的情况下创建集合视图的教程。你能在这里分享一些链接吗?谢谢大家的回答,但我想在不使用故事板的情况下创建一个集合视图。我的整个项目使用.xib文件。我找不到任何显示在没有故事板的情况下创建集合视图的教程。你能在这里分享一些链接吗?我想现在已经很晚了,但是对于其他还没有遇到这个问题的人来说,你可以通过编程的方式创建一个集合视图或几乎任何其他视图。对于集合视图,您只需以编程方式声明视图,就像您为uiview所做的那样。请记住,如果您使用的是flow layout,您也需要以编程方式声明布局。感谢各位的回答,但我希望在不使用故事板的情况下创建集合视图。我的整个项目使用.xib文件。我找不到任何显示在没有故事板的情况下创建集合视图的教程。你能在这里分享一些链接吗?我想现在已经很晚了,但是对于其他还没有遇到这个问题的人来说,你可以通过编程的方式创建一个集合视图或几乎任何其他视图。对于集合视图,您只需以编程方式声明视图,就像您为uiview所做的那样。请记住,如果您使用的是flow layout,您还需要以编程方式声明布局。