在scrollview中的每个元素上方放置标签?

时间:2017-05-16 03:45:09

标签: ios swift

我在for循环中填充我的scrollview并尝试在每个插入元素的顶部放置UILabel。但是,即使我将centerXAnchor设置为等于每个元素的centerXAnchor,标签也不会出于某种原因水平居中。这是一张带有标签和元素边框的图片:

scrollview

如图所示,由于某种原因,我插入的标签没有与滚动视图中的每个元素水平居中。这是我的for循环,我填充了scrollview:

for i in 0..<petsDict.count {
    let imageView = UIImageView()
    imageView.image = petsDict[i]
    imageView.contentMode = .scaleAspectFit
    let xPos = self.view.frame.width * CGFloat(i)
    imageView.frame = CGRect(x: xPos - CGFloat(20*i), y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)


    let label = UILabel(frame: CGRect(x: 0, y: -20, width: 200, height: 40))
    label.text = "Joy"
    label.textAlignment = .center
    imageView.addSubview(label)
    label.font = UIFont(name: "SFUIText-Regular", size: 20)!
    label.sizeToFit()

    mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
    mainScrollView.addSubview(imageView)

    label.centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
    label.bottomAnchor.constraint(equalTo: imageView.topAnchor).isActive = true
}

有人可以帮我理解为什么我的x居中工作不正常吗?

3 个答案:

答案 0 :(得分:0)

尝试删除label.sizeToFit(),此功能会调整标签大小。

答案 1 :(得分:0)

try:
    driver = webdriver.Remote('http://localhost:4723/wd/hub', ios_caps)
    run_iOS_tests(driver)
except selenium.common.exceptions.WebDriverException:
    driver = webdriver.Remote('http://localhost:4723/wd/hub', android_caps)
    run_android_tests(driver)

}

试试此代码

答案 2 :(得分:0)

将标签的宽度设置为与imageview宽度相同,并移除sizeToFit和anchor。您只需要添加已添加的textAlignment。

相关问题