如何创建Uiview对象的副本,并降低特定标签的字体大小,在该标签中以编程方式在Swift中制作视图



我已经在子视图上编程创建视图。

    let view1 = UIView(frame: CGRectMake(30, cgfloat  , 270, 120))
    view1.backgroundColor = UIColor.whiteColor()
    view1.layer.cornerRadius = 40.0

    let Attdate: UILabel = UILabel()
    Attdate.frame = CGRectMake(15, 10, 100, 25)
    Attdate.backgroundColor = UIColor.orangeColor()
    Attdate.textColor = UIColor.blackColor()
    Attdate.font = UIFont(name: "BebasNeue", size: 106)
    Attdate.textAlignment = NSTextAlignment.Left
    Attdate.text = AttDate.description
    view1.addSubview(Attdate)

我有一个数组作为服务器的响应字符串,它为我提供了一系列数据。我想将这些数据打印到标签中。标签应动态地称为每个阵列长度。就是这样,我正在尝试复制View1(我的Uiview对象)。我尝试了nskeyedarachiver(不确定它将如何帮助)。

extension UIView{
     {
     func copyView() -> AnyObject
     {
        return          NSKeyedUnarchiver.unarchiveObjectWithData(NSKeyedArchiver.archivedDataWithRootObject(self))!
     }
     }

并声明:

    let view1 = UIView()
    let copiedView = view1.copyView() as! UIView
    print("CopiedView:(copiedView)")

但是,没有运气:(另外,我尝试了许多语法来降低特定标签的字体尺寸,但似乎没有用。

请回复。

要降低特定标签的字体大小,有两个选项:

  1. 您可以将字体大小制成初始化器的一部分,因此您可以在每次创建一个字体时设置它,例如:

class CustomView: UIView {
    init(fontSizeOfLabel : CGFloat) {
        super.init(frame: CGRect(x: 30, y: 20, width: 270, height: 120))
        // all your normal code in here
         let Attdate: UILabel = UILabel()
         Attdate.font = UIFont(name: "BebasNeue", size: fontSizeOfLabel)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
  1. 或者您可以在其子视图上循环并在之后更改您已经创建了它:

var instance = CustomView()
for subview in instance.subviews {
    if var label = subview as? UILabel { //check if it can convert the subview into a UILabel, if it can it is your label
        label.font = UIFont(name: "BebasNeue", size: 70)
    }
}

我尚未测试第二个解决方案,我检查了第一个解决方案

最新更新