Создайте словарь из names:profileImageUrl
var namesWithUrl = [String : String]()
и вместо names.append(name)
do:
names.append(name)
namesWithUrl[name] = profileImageUrl
, так что теперь имя хранится в словаре с его правильным profileImageUrlи поэтому словарь будет выглядеть так:
[name1value : name1URl, name2value : name2URl, ...]
Тогда, если вы используете SDWebImage , вы можете сделать это очень просто:
self.optionA.setTitle(names, for: .normal)
self.optionA.backgroundColor = UIColor.orange
self.optionA.sd_setBackgroundImage(with: URL(namesWithUrl[name[1]]), for: .normal)
//If using the button image
self.optionB.setTitle(names[1], for: .normal)
self.optionB.backgroundColor = UIColor.orange
optionAImageView.sd_setImage(with: URL(namesWithUrl[name[1]]))
//if using a seperate imageView
Это позволит легко установить изображениев свой imageView, и вы можете просто добавить эту строку под каждым из них.
РЕДАКТИРОВАТЬ: Добавление видов изображения для просмотра с прокруткой.
Вы можете добавить представление изображения через раскадровку на вид прокруткиили вы можете добавить их программно следующим образом:
Сначала объявите их:
var imageViewA = UIImageView()
var imageViewB = UIImageView()
Затем мне нравится иметь функцию setupLayout для обработки моих представлений:
func setupLayout() {
pinionImagesScrollView.addsubview(imageViewA)
imageViewA.translatesAutoResizingMaskIntoConstraints = false
imageViewA.widthAnchor.constraint(equalTo: pinionImagesScrollView.widthAnchor, constant: -10).isActive = true
imageViewA.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageViewA.topAnchor.constraint(equalTo: pinionImagesScrollView.topAnchor, constant: -5).isActive = true
pinionImagesScrollView.addsubview(imageViewA)
imageViewB.translatesAutoResizingMaskIntoConstraints = false
imageViewB.widthAnchor.constraint(equalTo: pinionImagesScrollView.widthAnchor, constant: -10).isActive = true
imageViewB.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageViewB.topAnchor.constraint(equalTo: imageViewA.bottomAnchor, constant: -5).isActive = true
}
Там вы можете увидеть, как мы помещаем imageViewB ниже imageViewA, и ширина такая же, как у scrollview -10, что дает немного места.
, затем вызовите setupLayout()
в viewDidLoad()
.они будут пустыми, пока вы не разместите изображения на них.с optionAImageView.sd_setImage(with: URL(namesWithUrl[name[1]]))
Обновление:
Возможно, вам потребуется изменить строковую версию URL-адреса на URL для SD_setimage, например:
let optionAUrl = URL.init(string: nameUrls[names[0]])
imageView.sd_setImage(with: optionAUrl)
Ошибка индекса можетозначает, что вы неправильно инициализируете словарь, как я тестировал, и он должен работать нормально.
Обновление:
Проблема с вашим setupLayout заключается в том, что вы смешиваете автоматическое размещение с использованием фреймов.Я предполагаю, что ваши ограничения scrollViews определены в раскадровке, так что вот как вы должны настроить imageViews, чтобы ширина и высота были такими же, как у scrollView, и вы можете перемещаться между ними.Обратите внимание, что если вы хотите прокрутить по горизонтали, вам следует изучить использование UICollectionView.
В этом примере я создаю scrollView программно, вы можете просто сфокусироваться на imageViews, поскольку ваши ограничения сделаны в раскадровке.
import UIKit
class ViewController: UIViewController {
let scrollView = UIScrollView()
let imageViewA = UIImageView()
let imageViewB = UIImageView()
let imageViewC = UIImageView()
//Declaring the imageViews
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
// Do any additional setup after loading the view, typically from a nib.
}
func setupLayout() {
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
scrollView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
scrollView.backgroundColor = .gray
//setting up the size of the scrollView
scrollView.addSubview(imageViewA)
//This means we are using autoLayout, building the views and setting their size based on how their constraints relate to other objects
imageViewA.translatesAutoresizingMaskIntoConstraints = false
imageViewA.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
//Setting the imageViewA top anchor to the scrollView topanchor we are essentially saying the top of this imageView starts at the top of the scroll view
imageViewA.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -10).isActive = true
//Here the imageViews width is equal to the scrollViews width, (-10 is optional if you want it not to touch the edges)
imageViewA.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
//CenterXAnchor here I am making sure the imageView is centered in the scrollView
imageViewA.heightAnchor.constraint(equalTo: scrollView.heightAnchor, constant: -10).isActive = true
//same with the height
imageViewA.backgroundColor = .cyan
//Background just for my testing as I dont have any images to sue
imageViewA.contentMode = .scaleAspectFit
//This is how you want the image to scale into the view for when you set it.
scrollView.addSubview(imageViewB)
imageViewB.translatesAutoresizingMaskIntoConstraints = false
imageViewB.topAnchor.constraint(equalTo: imageViewA.bottomAnchor, constant: 10).isActive = true
//Because we want to scroll down, the top anchor of imageViewB is equal to the bottom anchor of imageViewA meaning the top of B starts at the bottom of A
imageViewB.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
imageViewB.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -10).isActive = true
//Height and widths are the same.
imageViewB.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
imageViewB.backgroundColor = .cyan
imageViewB.contentMode = scaleAspectFit
scrollView.addSubview(imageViewC)
imageViewC.translatesAutoresizingMaskIntoConstraints = false
imageViewC.topAnchor.constraint(equalTo: imageViewB.bottomAnchor, constant: 10).isActive = true
//imageViewCs top starts at bottom of B
imageViewC.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
imageViewC.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -10).isActive = true
imageViewC.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
imageViewC.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
//for the final view, it needs to be connected to the bottom so the scrollView is able to scroll.
imageViewC.backgroundColor = .cyan
imageViewC.contentMode = .scaleAspectFit
}
}
Это дает мне квадратный Scrollview, который показывает imageViewA и позволяет мне прокручивать вниз и видеть imageViewB, а затем imageView C
Вывод этого кода, scrollView установлен в centerYanchor of viewпоэтому он останавливается на середине, синие квадраты - это imageViews, image1 показывает, как он запускается, вы можете увидеть ImageViewA, затем image2 показывает, как вы можете перейти к следующему изображению: