iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 4
0

# 起

接續上篇所講到的,自動產生圖片取用的 static computed property,在專案中其實還有一個元件使用的次數非常多:UIButton ,這邊指的按鈕是圖片類型的按鈕,一般我們設置這類的按鈕會像這樣:

let button = UIButton()
button.setImage(UIImage(named: "backNormal"), for: .normal)
button.setImage(UIImage(named: "backPressed"), for: .highlighted)
button.setImage(UIImage(named: "backDisabled"), for: .disabled)

如果結合前一篇,會像這樣:

let button = UIButton()
button.setImage(.backNormal, for: .normal)
button.setImage(.backPressed, for: .highlighted)
button.setImage(.backDisabled, for: .disabled)

但這樣寫也是有個問題,按鈕只要重複使用,上面的設定就需要全部重打一次。

# 承

因此,我想到了一個跟 UIImage extension 類似的寫法

extension UIButton {
    static var back: UIButton {
        let button = UIButton()
        button.setImage(.backNormal, for: .normal)
        button.setImage(.backPressed, for: .highlighted)
        button.setImage(.backDisabled, for: .disabled)
        return button
    }
}

# 轉

這次的爬檔案,先過濾出有 normalpresseddisable,這幾個關鍵的圖檔,接著一樣針對這些檔案,使用 Python 幫我們寫 code。

爬檔案的 code 大概像這樣

for file in allFile:
    isImage = ".png" in file or  ".pdf" in file
    if not isImage: continue
    try:
        endIndex = str(file).index("@")
    except:
        endIndex = file.index(".")
    fileSet.add(file[0:endIndex])
    
for file in fileSet:
    lowerFile = file.lower()
    if "pressed" not in lowerFile and "normal" not in lowerFile and "disabled" not in lowerFile:
        continue
    else:
        engine.addFileWith(file)

轉成 swift code 的大概是這樣

def addFileWith(self, file):
        tmpfile = file
        if "_normal" in file:
            tmpfile = file.replace("_normal","")
        elif "Normal" in file:
            tmpfile = file.replace("Normal","")
        elif "Pressed" in file:
            tmpfile = file.replace("Pressed","")
        elif "_pressed" in file:
            tmpfile = file.replace("_pressed","")
        elif "Disabled" in file:
            tmpfile = file.replace("Disabled","")
        elif "_disabled" in file:
            tmpfile = file.replace("_disabled","")

        if tmpfile[-1:] == "_":
            tmpfile = tmpfile[:-1]
            print("sliced file ->", tmpfile)
            print("origin file ->", file)

        if tmpfile in self.buttonList.keys():
            # print("in key", lowerFile)
            self.buttonList[tmpfile].append(file)
        else:
            # print("not in key", lowerFile)
            self.buttonList[tmpfile] = [file]

    def __buttonStrf(self, varName, buttonInfos):
        scope  = "\n\n    static var %(varName)s: UIButton {\n" % {"varName": varName}
        scope += "        return UIButton().oh\n"
        for info in buttonInfos:
            if "Normal" in info or "normal" in info :
                scope += "            .backgroundImage(.%(info)s, for: .normal)\n" % {"info": info}
            if "Pressed" in info or "pressed" in info:
                scope += "            .backgroundImage(.%(info)s, for: .highlighted)\n" % {"info": info}
            if "Disabled" in info or "disabled" in info:
                scope += "            .backgroundImage(.%(info)s, for: .disabled)\n" % {"info": info}
        scope += "            .done()\n"   
        scope += "    }"
        return scope
    
    def output(self, fileName):
        print(self.buttonList)
        homedir = os.path.expanduser("~")

        file = open(f"{homedir}/Desktop/{fileName}.swift", "w+")

        today = datetime.datetime.today()

        header = f"""
//
//  {fileName}.swift
//  ohlulu
//
//  Created by OhButtonEngin.py on {today.strftime("%Y/%m/%d")}
//  Lastupdate on 2019/7/9
//  Copyright © 2019 ohlulu. All rights reserved.
//
        """ 

        result = """
%(header)s
import UIKit

extension UIButton {
"""
        print(len(self.buttonList))
        file.write(result %  {"header": header})
        for key in self.buttonList.keys():
            if len(self.buttonList[key]) == 1: continue
            file.write(self.__buttonStrf(key, self.buttonList[key]))

        file.write("\n}")
        file.close()

或者直接到 我的Github clone 。


上一篇
[Day 3] 自動化的應用 part.1
下一篇
# [Day 5] Alamofire - APIRouter
系列文
iOS 開發筆記本5

1 則留言

0
ytyubox
iT邦新手 5 級 ‧ 2019-09-20 00:52:32

不錯的應用!

ohlulu iT邦新手 5 級‧ 2019-09-20 13:34:02 檢舉

/images/emoticon/emoticon08.gif

我要留言

立即登入留言