2017-05-23 14 views
-2

for 루프를 사용하여 각 변수를 변수로 설정할 필요없이 프로그래밍 방식으로 3 UTextView을 만들어야합니다.프로그래밍 방식으로 3 UITextView 만들기

for i in 1...3 { 
    var textView = UITextView() 
    self.automaticallyAdjustsScrollViewInsets = false 

    textView.center = self.view.center 
    textView.textAlignment = NSTextAlignment.justified 
    textView.textColor = UIColor.blue 
    textView.backgroundColor = UIColor.lightGray 

    self.view.addSubview(textView) 
} 

어떻게 내가 할 수있는이 3 텍스트 뷰를 만들고 그것을 제어 할 수있는 능력을 가지고 : 여기

는 데모입니까?

+1

textView의 프레임을 설정하여 크기를 지정해야합니다. – brimstone

+0

* "제어 할 수있는 능력"*이 무엇을 의미합니까? – rmaddy

+0

우선, 같은 위치 (self.view.center)에서 textView를 작성합니다. 둘째, textView를 제어하려면 각 텍스트 전용 아웃룩 콘센트가 있어야합니다. – Roy

답변

1

클래스의 다른 메소드에서 또는 생성 된 for 루프 이후에도 생성 된 텍스트 뷰에 액세스해야하는 경우 해당 참조를 유지해야합니다.

각각을 보유 할 배열을 만듭니다. 그런 다음 나중에 배열을 사용하여 액세스 할 수 있습니다. 배열을 만드는 메소드에서만 이것을 필요로한다면 배열을 다른 지역 변수로 생성하십시오. 클래스의 다른 위치에서 텍스트보기에 액세스해야하는 경우 배열을 클래스의 적절한 것으로 만듭니다 (보기 컨트롤러).

var textViews = [UITextView]() 

다음 루프에서

는 추가 :

textViews.append(textView) 

나중에 필요에 따라 배열 또는 액세스 개별 요소를 통해 당신이 반복 할 수있는 텍스트 뷰에 액세스해야 할 때.

+0

고마워요, 그게 무엇을 찾고 있었는지 –

0

@rmaddy와 마찬가지로, 이러한 textViews를 배열에 저장해야합니다. 또한 간단한 해결책은 UITextView 각각에 태그를 지정하고 각각 할당 된 태그로 접속하시면됩니다 자동 레이아웃

class MyViewController : UIViewController { 
    var textViews = [UITextView]() 

    func createUI() -> Void { 
     for i in 1...3 { 
      var textView = UITextView() 
      self.automaticallyAdjustsScrollViewInsets = false 

      textView.center = self.view.center 
      textView.textAlignment = NSTextAlignment.justified 
      textView.textColor = UIColor.blue 
      textView.backgroundColor = UIColor.lightGray 

      self.view.addSubview(textView) 

      var vertContraint : NSLayoutConstraint 
      if (i == 1) { 
       vertContraint = NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0.0) 
      } else { 
       vertContraint = NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: textViews[i - 1], attribute: .bottom, multiplier: 1.0, constant: 8.0) 
      } 
      //Do the same for your leading, trailing edges 
      textView.addConstraints([/*vertContraint, leadingContr, trailingContr*/]) 
      textViews.append(textView) 
     }    
    } 
} 
0

로 좋은 재생하는 데 도움이 textViews에 제약 조건을 추가해야합니다. 여기

는 할당 태그의 데모입니다 :

for i in 1...5 { 
    var textView = UITextView() 
    self.automaticallyAdjustsScrollViewInsets = false 

    textView.center = self.view.center 
    textView.textAlignment = NSTextAlignment.justified 
    textView.textColor = UIColor.blue 
    textView.backgroundColor = UIColor.lightGray 
    textView.tag = i 
    self.view.addSubview(textView) 
} 

그리고 당신은 태그에 의해 할당 된 UITextView()에 액세스 할 수 있습니다

self.view.viewWithTag(1) 
self.view.viewWithTag(2) 
... 

는 희망이 도움이!

+0

고맙습니다. –