Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 有人能帮我理解这个代码吗_Ios_Swift - Fatal编程技术网

Ios 有人能帮我理解这个代码吗

Ios 有人能帮我理解这个代码吗,ios,swift,Ios,Swift,这是我在互联网上找到的创建自定义分段控件的代码。我在理解最后两个函数时遇到了问题,开始使用touch和布局子视图。这些函数的用途是什么?它们的代码具体做什么 最后,请原谅这个问题。我仍然是iOS开发的初学者,我只是在寻求帮助 @IBDesignable class CustomSegmentedControl : UIControl { private var labels = [UILabel]() var items = ["Item 1","Item 2"] {

这是我在互联网上找到的创建自定义分段控件的代码。我在理解最后两个函数时遇到了问题,开始使用touch布局子视图。这些函数的用途是什么?它们的代码具体做什么

最后,请原谅这个问题。我仍然是iOS开发的初学者,我只是在寻求帮助

@IBDesignable class CustomSegmentedControl : UIControl {
    private var labels = [UILabel]()
    var items = ["Item 1","Item 2"] {
        didSet {
            setUpLabels()
        }
    }
    var thumbView = UIView()
    var selectedIndex : Int = 0 {
        didSet {
            displayNewSelectedIndex()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }
    func setupView() {
        //layer.cornerRadius = frame.height / 2
        layer.borderColor = UIColor.blackColor().CGColor
        layer.borderWidth = 2

        backgroundColor = UIColor.clearColor()
        setUpLabels()

        insertSubview(thumbView, atIndex: 0)
    }
    func setUpLabels() {
        for label in labels {
            label.removeFromSuperview()
        }
        labels.removeAll(keepCapacity: true)
        for index in 1...items.count {
            let label = UILabel(frame: CGRectZero)
            label.text = items[index-1]
            label.textAlignment = .Center
            label.textColor = UIColor.blackColor()
            self.addSubview(label)
            labels.append(label)
        }
    }
    func displayNewSelectedIndex() {
        let label = labels[selectedIndex]
        self.thumbView.frame = label.frame
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        var selectFrame = self.bounds
        let newWidth = CGRectGetWidth(selectFrame) / CGFloat(items.count)
        selectFrame.size.width = newWidth
        thumbView.frame = selectFrame
        thumbView.backgroundColor = UIColor.grayColor()
        //thumbView.layer.cornerRadius = thumbView.frame.height / 2

        let labelHeight = self.bounds.height
        let labelWidth = self.bounds.width / CGFloat(labels.count)

        for index in 0..<labels.count {
            let label = labels[index]
            let xPosition = CGFloat(index) * labelWidth
            label.frame = CGRectMake(xPosition, 0, labelWidth, labelHeight)
        }
    }
    override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
        let location = touch.locationInView(self)
        var calculatedIndex : Int?

        for (index, item) in labels.enumerate() {
            if item.frame.contains(location) {
                calculatedIndex = index
            }

            if calculatedIndex != nil {
                selectedIndex = calculatedIndex!
                sendActionsForControlEvents(.ValueChanged)
            }
        }
        return false
    }
}
@IBDesignable类CustomSegmentedControl:UIControl{
私有变量标签=[UILabel]()
变量项目=[“项目1”、“项目2”]{
迪塞特{
设置标签()
}
}
var thumbView=UIView()
变量selectedIndex:Int=0{
迪塞特{
displayNewSelectedIndex()
}
}
重写初始化(帧:CGRect){
super.init(frame:frame)
setupView()
}
必需的初始化?(编码器aDecoder:NSCoder){
super.init(编码者:aDecoder)
setupView()
}
func setupView(){
//layer.cornerRadius=frame.height/2
layer.borderColor=UIColor.blackColor().CGColor
layer.borderWidth=2
backgroundColor=UIColor.clearColor()
设置标签()
insertSubview(拇指视图,索引:0)
}
func setUpLabels(){
用于标签中的标签{
label.removeFromSuperview()
}
labels.removeAll(keepCapacity:true)
对于1…items.count中的索引{
let label=UILabel(帧:CGRectZero)
label.text=项目[索引-1]
label.textAlignment=.Center
label.textColor=UIColor.blackColor()
self.addSubview(标签)
标签。附加(标签)
}
}
func displayNewSelectedIndex(){
let label=标签[selectedIndex]
self.thumbView.frame=label.frame
}
覆盖func布局子视图(){
super.layoutSubviews()
var selectFrame=self.bounds
让newWidth=CGRectGetWidth(selectFrame)/CGFloat(items.count)
选择frame.size.width=newWidth
thumbView.frame=选择frame
thumbView.backgroundColor=UIColor.grayColor()
//thumbView.layer.cornerRadius=thumbView.frame.height/2
设labelHeight=self.bounds.height
让labelWidth=self.bounds.width/CGFloat(labels.count)
对于0..Bool中的索引{
让位置=触摸。位置查看(自)
var calculatedIndex:Int?
对于标签中的(索引,项)。枚举(){
如果item.frame.contains(位置){
calculatedIndex=索引
}
如果计算指数!=零{
selectedIndex=calculatedIndex!
sendActionsForControlEvents(.ValueChanged)
}
}
返回错误
}
}

我可以解释一下begin跟踪方法,我想另一种是可以研究的

 /*** beginTrackingWithTouch.. method to customize tracking. ***/
    // Parameters : touch : this returns the touch that occurred at a certain point in the view. withEvent, returns the UIEvent
    // associated with the touch. 
    // Return Type: Boolean.
    override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
            let location = touch.locationInView(self)   // This line returns the location of touch in the view. This location is in CGPoint.
            var calculatedIndex : Int? 

            for (index, item) in labels.enumerate() {  /// enumeration of an array gives you sequence type of integer and corresponding element type of the array.
                if item.frame.contains(location) {     /// so labels.enumerate returns the key value pairs like so : [(0, labelatIndex0), (1, labelatIndex1).. and so on.]
                    calculatedIndex = index            /// here index is the key, and item is the value (label.)
    // So for every label/index pair, you check whether the touch happened on the label by getting the frame of the label and checking if location is a part of the frame
    /// You equate the index to calculatedIndex  
              }
    // Now you if your calculated index is a valid number, you class, which extends UIControl, will call its method stating the change of value(sendActionsForControlEvents).
    // This in turn, will send a message to all the targets that have been registered using addTarget:action:forControlEvents: method.
                if calculatedIndex != nil {  
                    selectedIndex = calculatedIndex!
                    sendActionsForControlEvents(.ValueChanged)
                }
            }

            return false
        }

请阅读官方文档:和。
layoutSubviews
仅从阅读方法说明就有点难以掌握。请阅读有关视图布局的官方指南。