当前位置: 首页 > 工具软件 > swift-2048 > 使用案例 >

swift - 使用UIView给页面添加方格

关志勇
2023-12-01
import UIKit

class ViewController: UIViewController {
    //设置方格维度
    var dimension = 4
    //数字格子宽度
    var width:CGFloat = 50
    //设置间距
    var padding:CGFloat = 4
    //用于保存数据
    var background:Array<UIView>!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.background = Array<UIView>()
        setUpGameMap()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func setUpGameMap(){
        var x:CGFloat = 50
        var y:CGFloat = 150
        
        for _ in 0..<dimension
        {
            x += padding + width
            y = 150
            for _ in 0..<dimension
            {
                let background = UIView(frame: CGRect(x: x, y: y, width: width, height: width))
                background.backgroundColor = UIColor.darkGray
                self.view.addSubview(background)
                self.background.append(background)
                y += padding + width
            }
        }
    }
}


进阶

TileView:

import UIKit
class TileView: UIView {
    let colorMap = [
        2:UIColor.red,
        4:UIColor.orange,
        8:UIColor.yellow,
        16:UIColor.green,
        32:UIColor.brown,
        64:UIColor.blue,
        128:UIColor.purple,
        256:UIColor.cyan,
        512:UIColor.lightGray,
        1024:UIColor.magenta,
        2048:UIColor.black
    ]
    var numberLabel:UILabel!
    var value:Int = 0
 /*   个人觉得这步不需要,如果有错误请指教!
    var value:Int = 0{
        didSet{
            backgroundColor = colorMap[value]
            numberLabel.text="\(value)"
        }
    }
 */
    init(pos:CGPoint,width:CGFloat,value:Int) {
        numberLabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: width))
        numberLabel.textColor = UIColor.white
        numberLabel.textAlignment = .center
        numberLabel.minimumScaleFactor = 0.5
        numberLabel.font = UIFont.systemFont(ofSize: 17)
        numberLabel.text = "\(value)"
        super.init(frame:CGRect(x: pos.x, y: pos.y, width: width, height: width))
        addSubview(numberLabel)
        self.value = value
        backgroundColor = colorMap[value]
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

ViewController:

import UIKit

class ViewController: UIViewController {
    //设置方格维度
    var dimension = 4
    //数字格子宽度
    var width:CGFloat = 50
    //设置间距
    var padding:CGFloat = 4
    //用于保存数据
    var background:Array<TileView>!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.background = Array<TileView>()
        setUpGameMap()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func setUpGameMap(){
        var x:CGFloat = 50
        var y:CGFloat = 150
        
        for _ in 0..<dimension
        {
            x += padding + width
            y = 150
            for _ in 0..<dimension
            {
                let value:Int = 2<<Int(arc4random_uniform(10)+1)
                let background = TileView(pos: CGPoint(x: x, y: y), width: width, value: value)
                self.view.addSubview(background)
                self.background.append(background)
                y += padding + width
            }
        }
    }
}

自定义UIView

ScoreView

import UIKit
enum ScoreType{
    case common
    case best
}
protocol ScoreViewProtocal {
    func changescore(value s:Int)
}
class ScoreView: UIView,ScoreViewProtocal {
    var label:UILabel!
    let defaultFrame = CGRect(x: 0, y: 0, width: 100, height: 30)
    var stype:String!
    var score:Int = 0{
        didSet{
            label.text = "\(stype!):\(score)"
        }
    }
    init(stype:ScoreType)
    {
        label = UILabel(frame: defaultFrame)
        label.textAlignment = .center
        super.init(frame:defaultFrame)
        self.stype = (stype == .common ? "分数":"最高分")
        backgroundColor = UIColor.orange
        label.font = UIFont.systemFont(ofSize: 17)
        label.textColor = UIColor.white
        self.addSubview(label)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func changescore(value s: Int) {
        score = s
    }
}

ViewController:

import UIKit

class ViewController: UIViewController {
    var score:ScoreView!
    var bestscore:ScoreView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpScoreLabels()

    }
    func setUpScoreLabels(){
        score = ScoreView(stype: .common)
        score.frame.origin = CGPoint(x: 50, y: 80)
        score.changescore(value: 0)
        self.view.addSubview(score)
        
        bestscore = ScoreView(stype: .best)
        bestscore.frame.origin = CGPoint(x: 170, y: 80)
        bestscore.changescore(value: 99)
        self.view.addSubview(bestscore)
    }
}

将各种控件的创建写成一个类

ViewFactory:

import UIKit
class ViewFactory {
    class func getDefaultFrame()->CGRect
    {
        let defaultFrame = CGRect(x: 0, y: 0, width: 100, height: 30)
        return defaultFrame
    }
    class func creatLabel(title:String)->UILabel
    {
        let label = UILabel()
        label.textColor = UIColor.blue
        label.backgroundColor = UIColor.white
        label.text = title
        label.frame = ViewFactory.getDefaultFrame()
        return label
    }
    class func creatButton(type:String,action:Selector,sender:UIViewController)->UIButton
    {
        let button = UIButton(frame: ViewFactory.getDefaultFrame())
        button.backgroundColor = UIColor.red
        button.setTitle("button", for: .normal)
        button.addTarget(sender, action: action, for: .touchUpInside)
        return button
    }
    class func creatTextField(value:String,action:Selector,sender:UITextFieldDelegate)->UITextField
    {
        let textField = UITextField(frame: ViewFactory.getDefaultFrame())
        textField.backgroundColor = UIColor.clear
        textField.textColor = UIColor.green
        textField.borderStyle = .roundedRect
        textField.adjustsFontSizeToFitWidth = true
        textField.delegate = sender
        return textField
    }
    class func creatSegment(items:[String],action:Selector,sender:UIViewController)->UISegmentedControl
    {
        let segment = UISegmentedControl(items: items)
        segment.frame = ViewFactory.getDefaultFrame()
        segment.isMomentary = false
        segment.addTarget(sender, action: action, for: .valueChanged)
        return segment
    }
    class func createControl(type:String,title:[String],action:Selector,sender:AnyObject)->UIView {
        switch type {
        case "label":
            return ViewFactory.creatLabel(title: title[0])
        case "button":
            return ViewFactory.creatButton(type: type, action: action, sender: sender as! UIViewController)
        case "textfield":
            return ViewFactory.creatTextField(value: title[0], action: action, sender: sender as! UITextFieldDelegate)
        case "segment":
            return ViewFactory.creatSegment(items: title, action: action, sender: sender as! UIViewController)
        default:
            return ViewFactory.creatLabel(title: title[0])
        }
    }
}

ViewController:

import UIKit
 
class ViewController: UIViewController,UITextFieldDelegate {
     
    var txtNum:UITextField!
    var segDimension:UISegmentedControl!
    var btn:UIButton!
     
    override func viewDidLoad() {
        super.viewDidLoad()
        setupControls()
    }
     
    func setupControls()
    {
        //创建文本标签
        let labelNum = ViewFactory.createLabel("阈值:")
        labelNum.frame = CGRect(x: 20, y: 100, width: 60, height: 30)
        self.view.addSubview(labelNum)
         
        let labelDm = ViewFactory.createLabel("维度:")
        labelDm.frame = CGRect(x: 20, y: 200, width: 60, height: 30)
        self.view.addSubview(labelDm)
         
        //创建文本输入框
        txtNum = ViewFactory.createTextField("", action: nil, sender:self)
        txtNum.frame = CGRect(x:80,y:100,width:200,height:30)
        txtNum.returnKeyType = UIReturnKeyType.Done
        self.view.addSubview(txtNum)
         
        //创建分段单选控件
        segDimension = ViewFactory.createSegment(["3x3", "4x4", "5x5"],
            action:"dimensionChanged:", sender:self)
        segDimension.frame = CGRect(x:80,y: 200,width: 200,height: 30)
        self.view.addSubview(segDimension)
        segDimension.selectedSegmentIndex = 1
         
        //创建按钮控件
        btn = ViewFactory.createButton("确定", action: nil, sender: self)
        btn.frame.origin = CGPointMake(80, 300)
        self.view.addSubview(btn)
    }
     
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        //收起键盘
        txtNum.resignFirstResponder()
        //打印出文本框中的值
        print(txtNum.text)
        return true
    }
     
    func dimensionChanged(sender:AnyObject) {
        print("dimensionChanged")
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
 类似资料: