2016-09-08 101 views
1

我是iOS自動佈局的新手。我想使用UIScrollView啓用尋呼來實現查看尋呼機。我將scrollView設置爲(w,h)爲(200,65),但scrollView的寬度在運行時始終爲240。結果,內容的偏移量,我添加到scrollView中的標籤與scrollView的寬度不匹配。他們爲什麼不同?我如何獲得正確的寬度?iOS UIScrollView的寬度與約束中設置的寬度不同

enter image description here enter image description here

private let contents = ["This is the 1st message", 
         "This is the 2nd message", 
         "This is the 3rd message"] 

@IBOutlet weak var scrollView: UIScrollView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    print("scrollView.bounds = \(scrollView.bounds)") 
    print("scrollView.frame = \(scrollView.frame)") 

    var x: CGFloat = 0 
    for content in contents { 
     let label = UILabel(frame: CGRectMake(x, 0, 0, 0)) 
     label.text = content 
     label.sizeToFit() 
     print("label.frame = \(label.frame)") 
     scrollView.addSubview(label) 
     x += scrollView.bounds.width 
    } 

    scrollView.contentSize = CGSizeMake(x, scrollView.bounds.height) 
} 

Output: 
scrollView.bounds = (0.0, 0.0, 240.0, 128.0) 
scrollView.frame = (80.0, 156.0, 240.0, 128.0) 
label.frame = (0.0, 0.0, 178.0, 20.3333333333333) 
label.frame = (240.0, 0.0, 185.666666666667, 20.3333333333333) 
label.frame = (480.0, 0.0, 182.333333333333, 20.3333333333333) 
+0

添加scrollview約束x和y位置。 –

+0

你當前的大小課程是什麼? –

+0

@MarcoSantarossa我當前的尺寸是wCompact hRegular –

回答

1

這裏你的問題是,您使用的是尺寸級別wCompact hRegular這個限制,所以如果你有其他尺寸類(例如不同的方位),你沒有這些約束可用。

要設置只爲iPhone我建議編程做了限制:

if (IDevice.currentDevice().userInterfaceIdiom == .Phone) { 
    // Set constraints or a different UIVIew here 
} 

如果你準備好您的iPhone應用程序只有你可以使用類大小Any-Any避免編程設置。

+1

謝謝!你是對的。在我將尺寸類設置爲wAny hAny之後,它可以作爲一種魅力! –