swift-for循环创建button

今天下午呢简单的写了一个登录界面如图:

swift-for循环创建button_第1张图片
0.0.png

中间的那三个按钮我是用for循环创建的(适配看起来有点墨迹- =凑活看吧~),代码如下:

        /**
          * 三个button
          * AppWidth: CGFloat = UIScreen.mainScreen().bounds.size.width
          * AppHeight: CGFloat = UIScreen.mainScreen().bounds.size.height
          */
        for index in 0 ..< 3  {
            //按钮
            let shareBtn = UIButton.init(frame: CGRectMake((AppWidth / 3) * CGFloat(index) + AppWidth / 3 / 3, 20, AppWidth / 3 / 3, AppWidth / 3 / 3))

            //图片名需要拼接下
            let imageStr = "share_"
            let imageName = imageStr + String(index)
            shareBtn.setImage(UIImage.init(named: imageName), forState: UIControlState.Normal)

            //我是先创建了一个backView把button都放在上面了, 方便适配
            backView.addSubview(shareBtn)
            
            //图片下的文字
            let shareLabel = UILabel.init(frame: CGRectMake((AppWidth / 3) * CGFloat(index) + AppWidth / 3 / 3, 30 + shareBtn.frame.size.height, shareBtn.frame.size.width, 10))
            shareLabel.textAlignment = NSTextAlignment.Center
            shareLabel.font = UIFont.systemFontOfSize(10)
            shareLabel.adjustsFontSizeToFitWidth = true

            //分别设置图片下文字和点击方法
           switch index {
            case 0:
                shareLabel.text = "微信登录"
                shareBtn.addTarget(self, action: #selector(tapped1), forControlEvents: UIControlEvents.TouchUpInside)
            case 1:
                shareLabel.text = "微博登录"
                shareBtn.addTarget(self, action: #selector(tapped2), forControlEvents: UIControlEvents.TouchUpInside)

            default:
                shareLabel.text = "QQ 登录"
                shareBtn.addTarget(self, action: #selector(tapped3), forControlEvents: UIControlEvents.TouchUpInside)

            }

我把图片的名字都改成顺序的, 比较方便创建

swift-for循环创建button_第2张图片
图片名字.png

按钮点击事件响应:

func tapped1() {
        print("111")
    }

    func tapped2() {
        print("222")
    }
    
    func tapped3() {
        print("333")
    }

0.0啊就是这样啦我觉得还挺方便的要是有什么更方便的方法希望能指教下哈~

你可能感兴趣的:(swift-for循环创建button)