簡體   English   中英

UIScrollView無法水平滾動

[英]UIScrollView cannot scroll horizontally

我在UIViewController中有一個UIScrollView,我希望它可以水平滾動。 我以編程方式通過循環將按鈕添加到ScrollView。 循環之后,將myScrollView.contentSize.width設置為buttonWidth * numberOfButtons 我還要仔細檢查以確保contentSize大於滾動視圖的框架(在這種情況下,滾動視圖的寬度為375)。

let numberOfButton = 7        
for index in 0..<numberOfButton {
    let button = UIButton()
    let frame = CGRect(x: 80 + (index * 80), y: 6, width: 60, height: 32)
    button.setTitle("Button" + String(index), forState: .Normal)
    button.frame = frame
    button.titleLabel?.font = UIFont(name: "Museo Sans", size: 16)
    button.setTitleColor(UIColor.blueColor(), forState: .Normal) 

    myScrollView.addSubview(button)
}
myScrollView.contentSize = CGSize(width: 100*numberOfButtons, height: 42)

當我運行代碼時,它僅出現在Button3(有7個按鈕)上,而我無法將其滾動到末尾。 但是,當我設置myScrollView.bounces = true我可以在周圍拖動scrollview並查看其他按鈕,但是它將彈回原始狀態。 任何幫助將非常感激。

改變這個

tagBar.contentSize = CGSize(width: 100*7, height: 42)

myScrollView.contentSize = CGSize(width: 100*7, height: 42)

我認為您的問題是在第一個按鈕上設置了X值。 我剛剛嘗試過此代碼,它可以正常工作

    let numberOfButtons = 7
    for index in 0..<numberOfButtons {
        let button = UIButton()
        let frame = CGRect(x: 8 + (index * 96), y: 6, width: 80, height: 32)
        button.setTitle("Button \(index)", for: .normal)
        button.frame = frame
        button.titleLabel?.font = UIFont(name: "Museo Sans", size: 16)
        button.setTitleColor(UIColor.blue, for: .normal)

        myScrollView.addSubview(button)
    }
    myScrollView.contentSize = CGSize(width: 100*numberOfButton, height: 42)

Rajeshkumar R給您的答案,或者更好地使用約束。 您可以在myScrollView的左側和第一個按鈕的左側之間設置一個約束(“前導空格”約束),然后在每個按鈕和上一個按鈕之間設置前導空格約束,並在完成循環時從上一個最后一個空格開始按鈕到myScrollView

這樣,您不必自己計算contentSize。 它還具有更好的可擴展性(例如,如果您具有不同大小的按鈕,則必須知道每個寬度,將它們全部求和,然后使用scrollView將元素之間以及第一個和最后一個之間的邊距相加...)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM