2014-11-27 17 views
22

Ở đây mã của tôi. Tôi đang chuyển hai giá trị vào số CGRectMake(..) và nhận và báo lỗi.làm thế nào để chuyển đổi giá trị Int32 thành CGFloat nhanh chóng?

let width = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width 
// return Int32 value 

let height = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height 
// return Int32 value 

myLayer?.frame = CGRectMake(0, 0, width, height) 
// returns error: '`Int32`' not convertible to `CGFloat` 

Làm cách nào để chuyển đổi Int32 thành CGFloat để không trả về lỗi?

Trả lời

51

Để chuyển đổi giữa các loại dữ liệu số tạo ra một thể hiện mới của các loại mục tiêu, đi qua các giá trị nguồn như tham số. Vì vậy, để chuyển đổi một Int32 đến một CGFloat:

let int: Int32 = 10 
let cgfloat = CGFloat(int) 

Trong trường hợp của bạn, bạn hoặc là có thể làm:

let width = CGFloat(CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width) 
let height = CGFloat(CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height) 

myLayer?.frame = CGRectMake(0, 0, width, height) 

hay:

let width = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width 
let height = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height 

myLayer?.frame = CGRectMake(0, 0, CGFloat(width), CGFloat(height)) 

Lưu ý rằng không có ngầm hay rõ ràng loại đúc giữa các loại số nhanh chóng, vì vậy bạn phải sử dụng cùng một mẫu để chuyển đổi một số Int thành Int32 hoặc thành UInt, v.v.

+1

Cảm ơn nó hoạt động tốt! – iosLearner

+0

Tôi tự hỏi, có an toàn khi thực hiện chuyển đổi này trên các hệ thống 32 bit, trong đó 'int32' là (vẫn) 32 bit, tuy nhiên' CGFloat' cũng là 32 bit. Có tính đến sau đó là một điểm nổi và [câu trả lời này] (http://stackoverflow.com/a/30260843/1492173), sẽ có sự mất chính xác. Nêu tôi sai vui long chân chỉnh tôi. –

2

Chỉ cần chuyển đổi một cách rõ ràng widthheight để CGFloat sử dụng CGFloat's initializer:

myLayer?.frame = CGRectMake(0, 0, CGFloat(width), CGFloat(height)) 
Các vấn đề liên quan