2017-10-14 52 views
-1

我已經有這個問題一段時間了,出於某種原因,我似乎無法找到答案。如果我想用10個UIlabels(使用編程)創建一個應用程序,我寧願創建一個函數,以便我可以說:createLabel(size: , position: , textColor: , text:)我的麻煩是,我不知道如何爲每個名稱創建不同的名稱,所以後來我可以分別引用他們每個人,如果我想改變每個文本。以下是我希望在函數中使用的所有參數。另外,我將如何創建一個可以更改多個標籤文本的功能,如changeText(label1: , label2: , text:)謝謝!使用不同變量的函數

var output = UILabel() 
    output = UILabel(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 100)) 
    output.center = CGPoint(x: screenSize.width/2, y: self.size.height * 0.08) 
    output.textAlignment = .right 
    output.textColor = UIColor.white 
    output.font = UIFont(name: "Helvetica-Light", size: 15.0) 
    output.numberOfLines = 0; 
    output.text = "12345" 
    output.font = output.font.withSize(80) 
    self.view?.addSubview(output) 

回答

0

我怎麼能對每一項創建一個不同的名字,所以後來我可以參考他們每個人單獨如果我想更改每個

的文字

要做到這一點,您可以將它們保存在字典中。

// Create data structure for labels 
var labels = [String: UILabel]() 

// Add label with unique name 
labels["uniqueName"] = createLabel(size: , position: , textColor: , text:) 

// Access label with uniqueName 
let label = labels["uniqueName"] 

我將如何創建一個將改變多個標籤的文字,就像changeText功能(LABEL1:,標籤2:文本:)

你可以寫你的函數類似這樣的

func changeText(text: String, labels: UILabel...) { 
    for label in labels { 
     label.text = text 
    } 
} 

查看關於可變參數的部分:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html瞭解更多關於此的內容。

0

至於我,使它最簡單的方法,就是用標籤,所以你可以爲每個標籤設置標籤(如1001,1002,1003 ......)和搜索之後發現確切的標籤通過標籤的子視圖:

if let view = self.view?.viewWithTag(put the tag here) as? UILabel { 
    //set any parameters here 
} 

也許有更好的辦法,不知道

+0

'UIView'有'viewWithTag'方法 – vadian

+0

@vadian謝謝,我編輯了我的答案,完全忘了它 – Woof

相關問題