以编程方式添加新的UIView,其中包含不同的数据

时间:2017-09-10 00:37:47

标签: ios swift uiview

背景:每次调用addButtonClicked动作时,我都需要创建一个可拖动的球,其中包含不同的数字和名称。无法真正理解这里的方法。球正在显示并正确移动但是如何为每个新球添加不同的数据?

是否可以为UIView创建类似原型单元格的东西?

class ViewController: UIViewController {
    //VAR
    var playerName = ""
    var number = ""
    var balls = [UIView]()

    @IBOutlet weak var ball: UIView!
    @IBOutlet weak var addButton: UIBarButtonItem!
    @IBOutlet weak var numberLabel: UILabel!

    @IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
        let translation = recognizer.translation(in: self.view)
        if let view = recognizer.view {
            view.center = CGPoint(x:view.center.x + translation.x,
                                  y:view.center.y + translation.y)
        }
        recognizer.setTranslation(CGPoint.zero, in: self.view)
    }

    // ACTIONS
    @IBAction func addButtonClicked(_ sender: Any) {
        let newBall=UIView(frame: CGRect(x: 10, y: 100, width: 50, height: 50))

        // Change UIView background colour
        newBall.backgroundColor=UIColor.white

        // Add rounded corners to UIView
        newBall.layer.cornerRadius=25

        // Add border to UIView
        newBall.layer.borderWidth=0

        let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        newBall.addGestureRecognizer(gestureRecognizer)

        // Add UIView as a Subview
        self.view.addSubview(newBall)

        balls.append(newBall)
        print ([balls])
    }

编辑:

当我添加let player1 = mycustomUIview())时,它说无法调用非函数类型'mycustomUIView'的值 如果我在ViewController中调用mycustomUiView.instantiatefromNib它会显示整个customView。 我的想法就是按一个+按钮创建不同的可拖动球,数据可以在里面改变(截图参考:https://imgur.com/a/fRiTE) 我尝试为每个玩家创建不同的UIViews,甚至是一个不同的viewController,但没有运气,我找不到在线的单一工作解决方案。

MyCustomUIViewController(从MyCustomUIView.xib连接的出口)

class playerBall: UIView {


@IBOutlet weak var contentView: UIView!
@IBOutlet weak var contentViewBall: UIView!
@IBOutlet weak var contentViewNumberLabel: UILabel!
@IBOutlet weak var contentViewNameLabel: UILabel!

// MARK: - Initializers

override init(frame: CGRect) {
    super.init(frame: frame)
    setupView()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupView()
}


// Performs the initial setup.
private func setupView() {
    let view = viewFromNibForClass()
    view.frame = bounds

    // Auto-layout
    view.autoresizingMask = [
        UIViewAutoresizing.flexibleWidth,
        UIViewAutoresizing.flexibleHeight
    ]

    // Show view.
    addSubview(view)
}

// Load XIB file into view and return this view.
 func viewFromNibForClass() -> UIView {

    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

    return view
}

}

MainViewController

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()


    playerBall.contentViewNameLabel.text = "Player"
    playerBall.contentViewNumberLabel.text = "10"

}



@IBOutlet weak var playerBall: playerBall!


@IBAction func buttonPressed(_ sender: Any) {



    var customView = playerBall.viewFromNibForClass()
    self.view.addSubview(customView)



 }   


}

1 个答案:

答案 0 :(得分:1)

我通过以下方式创建了您想要的效果: -

我创建了一个xib文件,我称之为PlayerBall.xib,我已添加到标签并更改背景颜色以清除颜色..

然后我创建了一个新的古柯触摸类PlayerBall.swift,它是UIView的子类。

将xib文件的类更改为PlayerBall而不是标准的UIView

将标签的出口连接到新创建的类。它应该如下所示:

class PlayerBall: UIView {

    @IBOutlet weak var playerNumber: UILabel!{
        didSet{
            playerNumber.layer.cornerRadius = playerNumber.frame.width / 2
            playerNumber.layer.masksToBounds = true
        }
    }

    @IBOutlet weak var playerName: UILabel!


    class func instanceFromNib() -> PlayerBall {
        return UINib(nibName: "PlayerBall", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! PlayerBall
    }

}

现在在主viewController中测试代码我添加了以下内容

override func viewDidLoad() {
    super.viewDidLoad()


    for i in 1...5 {
        let ball = PlayerBall.instanceFromNib()
        ball.playerNumber.text  = "\(i)"
        ball.playerName.text = "Player " + ball.playerNumber.text!
        let randomX = arc4random_uniform(UInt32(view.frame.width))
        let randomY = arc4random_uniform(UInt32(view.frame.height))
        ball.center = CGPoint(x: CGFloat(randomX), y: CGFloat(randomY))
        view.addSubview(ball)
    }


}

结果如下: the result

您可以为自定义类添加更多功能,我只是将其作为概念验证基础。

我希望这有帮助

相关问题