在CGRectMake,Swift,UIkit中使用变量

时间:2015-06-07 09:44:14

标签: ios xcode swift uikit

对于我正在使用的应用程序,我需要使用变量来更改对象的大小和位置(标签)。我试过[DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true), Display(Name = "Start Date")] public DateTime? StartDate { get; set; } [DataType(DataType.Time)] [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true), Display(Name = "Start Time")] public DateTime? StartTime { get; set; } [Display(Name = "Start Time")] public DateTime? FullStartTime { get { if(StartDate == null || StartTime == null) return null; return StartDate.Value.Date + StartTime.Value.TimeOfDay; //or return StartDate + StartTime; } } ,希望它会忽略零(不是真的以为)。然后我尝试了:

var example = CGRectMake(0, 0, 0, 100)

我稍微更改了语法,添加了“”并将var example = 100 Label1.frame = CGRectMake(20, 20, 50, example) 替换为CGRectMake等,但没有任何效果......我不知道我在这里做错了什么......救命啊!

4 个答案:

答案 0 :(得分:66)

Swift 3 update

let rect = CGRect(x: 0, y: 0, width: 100, height: 100)

答案 1 :(得分:4)

file_{01..20}.txt 获取CGRectMake个所有参数。如果您使用类型标识符指定CGFloat应该是example,那么您的示例代码应该可以正常工作:

CGFloat

否则,swift会将 // v~~~~ add this... var example: CGFloat = 100 Label1.frame = CGRectMake(20, 20, 50, example) 的类型推断为example,并且对Int的调用失败,因为它无法将CGRectMake作为参数...

答案 2 :(得分:1)

所以,有许多方法可以给猫皮肤。这一切都取决于您的需求和要求(也许您可以详细说明您要实现的目标?)。但是,一种方法是在发生某些事情时设置变量,然后更新标签的框架。如果您在视图中添加了点击手势识别器,并更新了标签,如下所示:

let myLabel = UILabel()

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGestRecog = UITapGestureRecognizer(target: self, action: "handleTap:")
    self.view.addGestureRecognizer(tapGestRecog)
}

func handleTap(sender:UIGestureRecognizer) {

    let newXposition = sender.locationInView(self.view).x
    let newYposition = sender.locationInView(self.view).y

    myLabel.frame = CGRectMake(newXposition, newYposition, 200, 200)
}

这只是一个例子,也是一种非常粗暴的做法。还有很多其他的方法,但它希望能让你了解如何实现它。

答案 3 :(得分:0)

Swift允许Objective-C没有的语法:

var example = 100
label.frame.size.height = example

在Objective-C中你必须采用不同的方式:

CGRect frame = label.frame;  //Create a temporary rect to hold the frame value
frame.size.height = example;
label.frame = frame;