2015-06-23 48 views
0

我想畫一個棋盤。在下面的代碼中,我得到了董事會的寬度和除以8就得到我需要繪製的平方大小,如下所示:制定UIView大小

let squareLength = CGFloat(self.bounds.size.width/8) 
var x:CGFloat = 0 
var y:CGFloat = 0 

for rowIndex in 1...8 { 

    // odd rows start indented 
    if (rowIndex % 2 == 1) { 
     x += squareLength 
    } 

    // draw this row 
    for colIndex in 1...4 { 
     let f:CGRect = CGRectMake(x, y, squareLength, squareLength) 
     let square = BlackSquare(frame: f) 
     addSubview(square) 

     x += squareLength * 2 
    } 

    // reset 
    x = 0 
    y += squareLength 
} 

我遇到的問題是,方塊在雙抽他們的點大小。

根據我的理解,self.bounds.size.width返回的值以及傳遞給我創建的框架的數字都在點中,所以它們應該匹配並且棋盤應該正確繪製?

換句話說,我該如何調整以解決這個問題?

這裏是繪圖代碼,從Square.swift:

import Foundation 
import UIKit 

class BlackSquare: UIView { 
    override init (frame : CGRect) { 
     super.init(frame : frame) 

     opaque = false 
     backgroundColor = UIColor.clearColor() 
    } 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override func drawRect(rect: CGRect) { 
     let ctx = UIGraphicsGetCurrentContext() 
     CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0) 
     CGContextSetLineWidth(ctx, 0.75) 

     let spacing = 4 
     let numLines = Int(Int(rect.width)/spacing) * 2 

     for index in 1...numLines { 
      let m = CGFloat(index * spacing) 
      let zero = CGFloat(0) 

      CGContextMoveToPoint(ctx, m, zero) 
      CGContextAddLineToPoint(ctx, zero, m) 
      CGContextStrokePath(ctx) 
     } 
    } 
} 
+0

你的理解是正確的,你的代碼看起來也是正確的,但是你需要提供更多的上下文。你用你計算的數值做什麼?顯示您的繪圖代碼。 –

+0

你在視網膜設備上測試嗎? – ndmeiri

+0

您能否以雙倍大小顯示董事會形象? – ndmeiri

回答

0

好,我想通了。在我上面的代碼中,函數是從init調用的,在一個視圖中,它的約束解決之前使用autolayout。回來的價值沒有意義。

我將調用移至layoutSubviews(),並且所有大小和數學運算符合預期。