有没有一种方法可以获取包含SwiftUI中内容的ScrollView的高度?

时间:2020-06-02 07:36:08

标签: swiftui

我想计算从整个ScrollView的高度到ScrollView的底部可以滚动多少,但我无法获得整个ScrollView的高度。 如果有任何方法可以解决,请告诉我。

scrollView.contentSize.height scrollView.frame.height

前两个是您想要获取的值

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import mpl


x1 = np.arange(10)   
x2 = x1*10 
y1 = x1*2
y2 = x1*10000

def adjust_subplot_layout(fig):
    for ax in fig.axes:
        x0,x1 = ax.get_xlim()
        y0,y1 = ax.get_ylim()
        ax.set_aspect((x1-x0)/(y1-y0))

def squarify(fig):
    adjust_subplot_layout(fig)

fig = plt.figure(figsize=(6,4))

display_mode = 1 # 1 show the legend right
value = mpl.rcParams['figure.subplot.right']
print(value)
x = 1.6
if display_mode == 1:
    loc_val = "upper right"
    bbox_anchor = (value +x ,1.0)
else:
    loc_val = "lower left"
    bbox_anchor = (0., 1.02, 1., .102)

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,1,frameon=False,sharex=ax1)
lg1 = ax1.plot(x1,y1,label='ax1')
lg2 = ax2.plot(x2,y2,label='ax2',color='tab:red')
ax2.get_yaxis().set_ticks_position('right')
ax1.tick_params(axis='x', labelcolor='tab:blue') 
ax1.tick_params(axis='y', labelcolor='tab:red') 
ax2.tick_params(axis='y', labelcolor='tab:red') 
lga = lg1 + lg2
labs = [l.get_label() for l in lga]

if display_mode == 1:
    ax1.legend(lga, labs, loc=loc_val ,bbox_to_anchor=bbox_anchor)
else:
    ax1.legend(lga, labs, loc=loc_val ,bbox_to_anchor=bbox_anchor, ncol=2, borderaxespad=0.)
ax1.set_ylabel("ax1-ylabel")
ax2.set_ylabel("ax2-ylabel")
ax2.get_yaxis().set_label_position("right")


ax3 = fig.add_subplot(2,2,2)
ax4 = fig.add_subplot(2,2,2,frameon=False,sharex=ax3)
lg3 = ax3.plot(x1,y1,label='ax3')
lg4 = ax4.plot(x2,y2,label='ax4',color='tab:red')
ax4.get_yaxis().set_ticks_position('right')
ax3.tick_params(axis='x', labelcolor='tab:blue') 
ax3.tick_params(axis='y', labelcolor='tab:red') 
ax4.tick_params(axis='y', labelcolor='tab:red') 
lgb = lg3 + lg4
labs = [l.get_label() for l in lgb]

if display_mode == 1:
    ax3.legend(lga, labs, loc=loc_val ,bbox_to_anchor=bbox_anchor)
else:
    ax3.legend(lga, labs, loc=loc_val ,bbox_to_anchor=bbox_anchor, ncol=2, borderaxespad=0.)

ax3.set_ylabel("ax3-ylabel")
ax4.set_ylabel("ax4-ylabel")
ax4.get_yaxis().set_label_position("right")

ax5 = fig.add_subplot(2,2,3)
ax6 = fig.add_subplot(2,2,3,frameon=False,sharex=ax5)
lg5 = ax5.plot(x1,y1,label='ax5')
lg6 = ax6.plot(x2,y2,label='ax6',color='tab:red')
ax6.get_yaxis().set_ticks_position('right')
ax5.tick_params(axis='x', labelcolor='tab:blue') 
ax5.tick_params(axis='y', labelcolor='tab:red') 
ax6.tick_params(axis='y', labelcolor='tab:red') 
ax6.get_yaxis().set_label_position("right")
lgc = lg5 + lg6
labs = [l.get_label() for l in lgc]
if display_mode == 1:
    ax5.legend(lga, labs, loc=loc_val ,bbox_to_anchor=bbox_anchor)
else:
    ax5.legend(lga, labs, loc=loc_val ,bbox_to_anchor=bbox_anchor, ncol=2, borderaxespad=0.)
ax5.set_ylabel("ax5-ylabel")
ax6.set_ylabel("ax6-ylabel")


fig.set_tight_layout(True)
adjust_subplot_layout(fig)
#fig.canvas.mpl_connect("draw_event", lambda evt: squarify(fig))
#fig.tight_layout()
plt.show()


1 个答案:

答案 0 :(得分:0)

这是一个基于How to make a SwiftUI List scroll automatically?答案中的ViewHeightKey首选项键的解决方案

var body: some View {
    ScrollView {
        VStack {
            ForEach(0..<100, id: \.self) { number in
                Text("\(number)")
            }
        }
        .modifier(ViewHeightKey())   // calculate here !!
    }
    .onPreferenceChange(ViewHeightKey.self) { // read here !!
        print("Content height: \($0)")
    }
    .background(GeometryReader { gp -> Color in
        let frame = gp.frame(in: .local)
        print("ScrollView height: \(frame.size.height)")
        return Color.clear
    })
}